GOOGLE CLOUD PLATFORM'DA JAVA

Ücretsiz Deneyin Belgeleri Görüntüle

Yüksek Düzeyde Ölçeklenebilir Java Uygulamaları Geliştirme, Dağıtma, İzleme ve Uygulamalarda Hata Ayıklama

  • Eclipse, IntelliJ ya da tarayıcı tabanlı komut satırını kullanarak GCP üzerinde Java uygulamaları geliştirin
  • Spring Boot ya da Spark Java uygulamalarını dağıtın veya ölçeklendirin
  • GCP üzerinde uygulama geliştirmek ve dağıtmak için Maven ya da Gradle geliştirme araçları eklentilerini kullanın.
  • Java'yı kullanarak tümüyle GCP üzerinde yönetilen MySQL, PostgreSQL ya da NoSQL veritabanlarında sorgulama yapın
  • Yönetilen bir Kubernetes kümesine Java uygulamaları dağıtın
  • Google tarafından yönetilen OpenJDK veya OpenJDK+Jetty9 Docker görüntüleri üzerinde uygulama çalıştırın
Kapsamlı Deyimsel Java API'leri ve Kitaplıklar
Cloud Storage'da veri depolayın ve arşivleyin
Pub/Sub ile tümüyle yönetilen, olay odaklı mesajlaşma ayarlayın
BigQuery kullanarak herkese açık verileri sorgulayın
Translation API ile metinleri farklı dillere çevirin
Vision API ile görüntüleri analiz edin
Cloud Storage'da veri depolayın ve arşivleyin
1
Cloud Platform Console projesi oluşturun
  1. Sign in to your Google Account.

    If you don't already have one, sign up for a new account.

  2. Set up a GCP Console project.

    Set up a project

    Click to:

    • Create or select a project.
    • Enable the Cloud Storage API for that project.
    • Create a service account.
    • Download a private key as JSON.

    You can view and manage these resources at any time in the GCP Console.

2
Cloud Storage Paketi kurun

Cloud Storage Paketi oluşturun:

gsutil mb gs://[YOUR-BUCKET-NAME]

Dosya yayınlayabilmesi için paketi herkese açık şekilde ayarlayın:

gsutil defacl set public-read gs://[YOUR_BUCKET_NAME]
3
pom.xml dosyasına maven bağımlılıkları ekleyin
<dependency>
  <groupId>com.google.cloud</groupId>
  <artifactId>google-cloud-storage</artifactId>
  <version>1.22.0</version>
</dependency>
4
app.yaml dosyasına ortam değişenleri ekleyin
env_variables:
  BUCKET_NAME: YOUR-BUCKET-NAME
5
Kodunuzu yazın
@SuppressWarnings("serial")
@WebServlet(name = "upload", value = "/upload")
@MultipartConfig()
public class UploadServlet extends HttpServlet {

  private static final String BUCKET_NAME = System.getenv("BUCKET_NAME");
  private static Storage storage = null;

  @Override
  public void init() {
    storage = StorageOptions.getDefaultInstance().getService();
  }

  @Override
  public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException,
      ServletException {
    final Part filePart = req.getPart("file");
    final String fileName = filePart.getSubmittedFileName();

    // Modify access list to allow all users with link to read file
    List<Acl> acls = new ArrayList<>();
    acls.add(Acl.of(Acl.User.ofAllUsers(), Acl.Role.READER));
    // the inputstream is closed by default, so we don't need to close it here
    Blob blob =
        storage.create(
            BlobInfo.newBuilder(BUCKET_NAME, fileName).setAcl(acls).build(),
            filePart.getInputStream());

    // return the public download link
    resp.getWriter().print(blob.getMediaLink());
  }
}
Pub/Sub ile tamamen yönetilebilir, olay odaklı mesajlaşma ayarlayın
1
Cloud Platform Console projesi oluşturun
  1. Sign in to your Google Account.

    If you don't already have one, sign up for a new account.

  2. Set up a GCP Console project.

    Set up a project

    Click to:

    • Create or select a project.
    • Enable the Cloud Pub/Sub API for that project.
    • Create a service account.
    • Download a private key as JSON.

    You can view and manage these resources at any time in the GCP Console.

2
Konu ve abonelik oluşturun
gcloud beta pubsub topics create YOUR_TOPIC_NAME
gcloud beta pubsub subscriptions create YOUR_SUBSCRIPTION_NAME --topic YOUR_TOPIC_NAME
3
pom.xml dosyasına maven bağımlılıkları ekleyin
<dependency>
  <groupId>com.google.cloud</groupId>
  <artifactId>google-cloud-pubsub</artifactId>
  <version>1.62.0</version>
</dependency>
4
Mesajları yayınlamak ve almak için kodunuzu yazın

Mesaj Yayınlama

import com.google.api.core.ApiFuture;
import com.google.api.core.ApiFutureCallback;
import com.google.api.core.ApiFutures;
import com.google.api.gax.rpc.ApiException;
import com.google.cloud.ServiceOptions;
import com.google.cloud.pubsub.v1.Publisher;
import com.google.protobuf.ByteString;
import com.google.pubsub.v1.ProjectTopicName;
import com.google.pubsub.v1.PubsubMessage;

public class PublisherExample {

  // use the default project id
  private static final String PROJECT_ID = ServiceOptions.getDefaultProjectId();

  /** Publish messages to a topic.
   * @param args topic name, number of messages
   */
  public static void main(String... args) throws Exception {
    // topic id, eg. "my-topic"
    String topicId = args[0];
    int messageCount = Integer.parseInt(args[1]);
    ProjectTopicName topicName = ProjectTopicName.of(PROJECT_ID, topicId);
    Publisher publisher = null;
    try {
      // Create a publisher instance with default settings bound to the topic
      publisher = Publisher.newBuilder(topicName).build();

      for (int i = 0; i < messageCount; i++) {
        String message = "message-" + i;

        // convert message to bytes
        ByteString data = ByteString.copyFromUtf8(message);
        PubsubMessage pubsubMessage = PubsubMessage.newBuilder()
            .setData(data)
            .build();

        //schedule a message to be published, messages are automatically batched
        ApiFuture<String> future = publisher.publish(pubsubMessage);

        // add an asynchronous callback to handle success / failure
        ApiFutures.addCallback(future, new ApiFutureCallback<String>() {

          @Override
          public void onFailure(Throwable throwable) {
            if (throwable instanceof ApiException) {
              ApiException apiException = ((ApiException) throwable);
              // details on the API exception
              System.out.println(apiException.getStatusCode().getCode());
              System.out.println(apiException.isRetryable());
            }
            System.out.println("Error publishing message : " + message);
          }

          @Override
          public void onSuccess(String messageId) {
            // Once published, returns server-assigned message ids (unique within the topic)
            System.out.println(messageId);
          }
        });
      }
    } finally {
      if (publisher != null) {
        // When finished with the publisher, shutdown to free up resources.
        publisher.shutdown();
      }
    }
  }
}

Mesajlara Abone Olma

import com.google.cloud.ServiceOptions;
import com.google.cloud.pubsub.v1.AckReplyConsumer;
import com.google.cloud.pubsub.v1.MessageReceiver;
import com.google.cloud.pubsub.v1.Subscriber;
import com.google.pubsub.v1.ProjectSubscriptionName;
import com.google.pubsub.v1.PubsubMessage;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;

public class SubscriberExample {

  // use the default project id
  private static final String PROJECT_ID = ServiceOptions.getDefaultProjectId();

  private static final BlockingQueue<PubsubMessage> messages = new LinkedBlockingDeque<>();

  static class MessageReceiverExample implements MessageReceiver {

    @Override
    public void receiveMessage(PubsubMessage message, AckReplyConsumer consumer) {
      messages.offer(message);
      consumer.ack();
    }
  }

  /** Receive messages over a subscription. */
  public static void main(String... args) throws Exception {
    // set subscriber id, eg. my-sub
    String subscriptionId = args[0];
    ProjectSubscriptionName subscriptionName = ProjectSubscriptionName.of(
        PROJECT_ID, subscriptionId);
    Subscriber subscriber = null;
    try {
      // create a subscriber bound to the asynchronous message receiver
      subscriber =
          Subscriber.newBuilder(subscriptionName, new MessageReceiverExample()).build();
      subscriber.startAsync().awaitRunning();
      // Continue to listen to messages
      while (true) {
        PubsubMessage message = messages.take();
        System.out.println("Message Id: " + message.getMessageId());
        System.out.println("Data: " + message.getData().toStringUtf8());
      }
    } finally {
      if (subscriber != null) {
        subscriber.stopAsync();
      }
    }
  }
}
BigQuery ile veri analizi gerçekleştirme
1
Cloud Platform Console projesi oluşturun
  1. Sign in to your Google Account.

    If you don't already have one, sign up for a new account.

  2. Set up a GCP Console project.

    Set up a project

    Click to:

    • Create or select a project.
    • Enable the BigQuery API for that project.
    • Create a service account.
    • Download a private key as JSON.

    You can view and manage these resources at any time in the GCP Console.

2
pom.xml dosyasına maven bağımlılıkları ekleyin
<dependency>
  <groupId>com.google.cloud</groupId>
  <artifactId>google-cloud-bigquery</artifactId>
  <version>1.62.0</version>
</dependency>
3
Kodunuzu Yazın

BigQuery hizmet nesnesi oluşturma

BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService();

Herkese Açık Verileri Sorgulama

QueryJobConfiguration queryConfig =
    QueryJobConfiguration.newBuilder(
      "SELECT "
          + "CONCAT('https://stackoverflow.com/questions/', CAST(id as STRING)) as url, "
          + "view_count "
          + "FROM `bigquery-public-data.stackoverflow.posts_questions` "
          + "WHERE tags like '%google-bigquery%' "
          + "ORDER BY favorite_count DESC LIMIT 10")
        // Use standard SQL syntax for queries.
        // See: https://cloud.google.com/bigquery/sql-reference/
        .setUseLegacySql(false)
        .build();

// Create a job ID so that we can safely retry.
JobId jobId = JobId.of(UUID.randomUUID().toString());
Job queryJob = bigquery.create(JobInfo.newBuilder(queryConfig).setJobId(jobId).build());

// Wait for the query to complete.
queryJob = queryJob.waitFor();

// Check for errors
if (queryJob == null) {
  throw new RuntimeException("Job no longer exists");
} else if (queryJob.getStatus().getError() != null) {
  // You can also look at queryJob.getStatus().getExecutionErrors() for all
  // errors, not just the latest one.
  throw new RuntimeException(queryJob.getStatus().getError().toString());
}

Sonuçları Görüntüleme

// Get the results.
QueryResponse response = bigquery.getQueryResults(jobId);

TableResult result = queryJob.getQueryResults();

// Print all pages of the results.
for (FieldValueList row : result.iterateAll()) {
  String url = row.get("url").getStringValue();
  long viewCount = row.get("view_count").getLongValue();
  System.out.printf("url: %s views: %d%n", url, viewCount);
}
Translation API ile metinleri farklı dillere çevirin
1
Cloud Platform Console projesi oluşturun
  1. Sign in to your Google Account.

    If you don't already have one, sign up for a new account.

  2. Set up a GCP Console project.

    Set up a project

    Click to:

    • Create or select a project.
    • Enable the Cloud Translation API for that project.
    • Create a service account.
    • Download a private key as JSON.

    You can view and manage these resources at any time in the GCP Console.

2
pom.xml dosyasına maven bağımlılıkları ekleyin
<dependency>
  <groupId>com.google.cloud</groupId>
  <artifactId>google-cloud-translate</artifactId>
  <version>1.62.0</version>
</dependency>
3
Kodunuzu Yazın
// Imports the Google Cloud client library
import com.google.cloud.translate.Translate;
import com.google.cloud.translate.Translate.TranslateOption;
import com.google.cloud.translate.TranslateOptions;
import com.google.cloud.translate.Translation;

public class QuickstartSample {
  public static void main(String... args) throws Exception {
    // Instantiates a client
    Translate translate = TranslateOptions.getDefaultInstance().getService();

    // The text to translate
    String text = "Hello, world!";

    // Translates some text into Russian
    Translation translation =
        translate.translate(
            text,
            TranslateOption.sourceLanguage("en"),
            TranslateOption.targetLanguage("ru"));

    System.out.printf("Text: %s%n", text);
    System.out.printf("Translation: %s%n", translation.getTranslatedText());
  }
}
Vision API ile görüntüleri analiz edin
1
Cloud Platform Console projesi oluşturun
  1. Sign in to your Google Account.

    If you don't already have one, sign up for a new account.

  2. Set up a GCP Console project.

    Set up a project

    Click to:

    • Create or select a project.
    • Enable the Cloud Vision API for that project.
    • Create a service account.
    • Download a private key as JSON.

    You can view and manage these resources at any time in the GCP Console.

2
pom.xml dosyasına maven bağımlılıkları ekleyin
<dependency>
  <groupId>com.google.cloud</groupId>
  <artifactId>google-cloud-vision</artifactId>
  <version>1.62.0</version>
</dependency>
<dependency>
  <groupId>com.google.cloud</groupId>
  <artifactId>google-cloud-storage</artifactId>
  <version>1.62.0</version>
</dependency>
3
Kodunuzu Yazın

Vision Hizmeti Alma

/**
 * Connects to the Vision API using Application Default Credentials.
 */
public static Vision getVisionService() throws IOException, GeneralSecurityException {
  GoogleCredential credential =
      GoogleCredential.getApplicationDefault().createScoped(VisionScopes.all());
  JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
  return new Vision.Builder(GoogleNetHttpTransport.newTrustedTransport(), jsonFactory, credential)
          .setApplicationName(APPLICATION_NAME)
          .build();
}

Yüz Algılama

/**
 * Gets up to {@code maxResults} faces for an image stored at {@code path}.
 */
public List<FaceAnnotation> detectFaces(Path path, int maxResults) throws IOException {
  byte[] data = Files.readAllBytes(path);

  AnnotateImageRequest request =
      new AnnotateImageRequest()
          .setImage(new Image().encodeContent(data))
          .setFeatures(ImmutableList.of(
              new Feature()
                  .setType("FACE_DETECTION")
                  .setMaxResults(maxResults)));
  Vision.Images.Annotate annotate =
      vision.images()
          .annotate(new BatchAnnotateImagesRequest().setRequests(ImmutableList.of(request)));
  // Due to a bug: requests to Vision API containing large images fail when GZipped.
  annotate.setDisableGZipContent(true);

  BatchAnnotateImagesResponse batchResponse = annotate.execute();
  assert batchResponse.getResponses().size() == 1;
  AnnotateImageResponse response = batchResponse.getResponses().get(0);
  if (response.getFaceAnnotations() == null) {
    throw new IOException(
        response.getError() != null
            ? response.getError().getMessage()
            : "Unknown error getting image annotations");
  }
  return response.getFaceAnnotations();
}

Yüzleri vurgulama

/**
 * Reads image {@code inputPath} and writes {@code outputPath} with {@code faces} outlined.
 */
private static void writeWithFaces(Path inputPath, Path outputPath, List<FaceAnnotation> faces)
    throws IOException {
  BufferedImage img = ImageIO.read(inputPath.toFile());
  annotateWithFaces(img, faces);
  ImageIO.write(img, "jpg", outputPath.toFile());
}

/**
 * Annotates an image {@code img} with a polygon around each face in {@code faces}.
 */
public static void annotateWithFaces(BufferedImage img, List<FaceAnnotation> faces) {
  for (FaceAnnotation face : faces) {
    annotateWithFace(img, face);
  }
}

/**
 * Annotates an image {@code img} with a polygon defined by {@code face}.
 */
private static void annotateWithFace(BufferedImage img, FaceAnnotation face) {
  Graphics2D gfx = img.createGraphics();
  Polygon poly = new Polygon();
  for (Vertex vertex : face.getFdBoundingPoly().getVertices()) {
    poly.addPoint(vertex.getX(), vertex.getY());
  }
  gfx.setStroke(new BasicStroke(5));
  gfx.setColor(new Color(0x00ff00));
  gfx.draw(poly);
}
JAVA HIZLI BAŞLANGIÇ KILAVUZLARI
Üretimle İlgili Sorunları Bulma ve Düzeltme

Google Stackdriver; güçlü takip, hata ayıklama günlüğü, izleme ve raporlama özellikleri sunar. Bulut tabanlı uygulamaların durumu, performansı ve kullanılabilirliği hakkında size analizler sunarak sorunları daha hızlı bulup çözmenize olanak tanır.

Daha fazla bilgi
GCP TOPLULUKLARINDA JAVA

Söyleyecekleriniz mi var? Soru sormak veya Google Cloud Platform'da Java destek kaynaklarının oluşturulmasına yardımcı olan Google uzmanlarıyla sohbet etmek için topluluğumuza katılın.