יצירת אפליקציית Java בסביבה הגמישה ב-App Engine

מזהה אזור

‫REGION_ID הוא קוד מקוצר ש-Google מקצה על סמך האזור שבוחרים כשיוצרים את האפליקציה. הקוד לא תואם למדינה או למחוז, למרות שחלק ממזהי האזורים עשויים להיראות דומים לקודים נפוצים של מדינות ומחוזות. באפליקציות שנוצרו אחרי פברואר 2020, המחרוזת REGION_ID.r כלולה בכתובות URL של App Engine. באפליקציות קיימות שנוצרו לפני התאריך הזה, מזהה האזור הוא אופציונלי בכתובת ה-URL.

מידע נוסף על מזהי אזורים

במדריך למתחילים הזה נסביר איך ליצור ולפרוס אפליקציה שמציגה הודעה קצרה. אפליקציית הדוגמה משתמשת ב-Java גרסה 17.

לפני שמתחילים

במדריך הזה למתחילים מניחים שהתקנתם את ערכת הפיתוח (JDK) של Java SE 17 במחשב המקומי.
  1. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  2. Verify that billing is enabled for your Google Cloud project.

  3. Enable the Cloud Build API, if it is not already enabled.

    Roles required to enable APIs

    To enable APIs, you need the serviceusage.services.enable permission. If you created the project, then you likely already have this permission through the Owner role (roles/owner). Otherwise, you can get this permission through the Service Usage Admin role (roles/serviceusage.serviceUsageAdmin). Learn how to grant roles.

    Enable the API

  4. Install the Google Cloud CLI.

  5. Configure the gcloud CLI to use your federated identity.

    For more information, see Sign in to the gcloud CLI with your federated identity.

  6. To initialize the gcloud CLI, run the following command:

    gcloud init

התפקידים הנדרשים

כדי לקבל את ההרשאות שדרושות להשלמת המדריך הזה, אתם צריכים לבקש מהאדמין להקצות לכם את תפקידי ה-IAM הבאים:

להסבר על מתן תפקידים, ראו איך מנהלים את הגישה ברמת הפרויקט, התיקייה והארגון.

יכול להיות שאפשר לקבל את ההרשאות הנדרשות גם באמצעות תפקידים בהתאמה אישית או תפקידים מוגדרים מראש.

דרישות מוקדמות נוספות

  1. מאתחלים את אפליקציית App Engine עם הפרויקט ובוחרים את האזור שלה:

    gcloud app create --project=[YOUR_PROJECT_ID]
    

    כשמופיעה בקשה, בוחרים את האזור שבו רוצים למקם את אפליקציית App Engine.

  2. מתקינים את הרכיבים הבאים במחשב המקומי:

המיקומים של App Engine

‫App Engine הוא אזורי, כלומר התשתית שמריצה את האפליקציות שלכם ממוקמת באזור ספציפי, ו-Google מנהלת אותה כך שהיא זמינה באופן יתירתי בכל התחומים באזור הזה.

הקריטריונים העיקריים לבחירת האזור שבו האפליקציות שלכם יפעלו הם זמן האחזור, הזמינות או העמידות. בדרך כלל אפשר לבחור את האזור הקרוב ביותר למשתמשים של האפליקציה, אבל כדאי גם לבדוק איפה App Engine זמין וגם את המיקומים שלGoogle Cloud המוצרים והשירותים האחרים שהאפליקציה משתמשת בהם. שימוש בשירותים בכמה מיקומים יכול להשפיע על זמן האחזור של האפליקציה וגם על התמחור שלה.

אחרי שמגדירים את האזור של האפליקציה, אי אפשר לשנות אותו.

אם כבר יצרתם אפליקציית App Engine, תוכלו לראות את האזור שלה באחת מהדרכים הבאות:

הורדה של אפליקציית Hello World

יצרנו אפליקציית Hello World ל-App Engine כדי שתוכלו להבין במהירות איך פורסים אפליקציה ב- Google Cloud.

  1. משכפלים את מאגר אפליקציית הדוגמה Hello World למחשב המקומי.

    git clone https://github.com/GoogleCloudPlatform/java-docs-samples
    

    אפשרות נוספת היא להוריד את הקובץ לדוגמה כקובץ ZIP ולחלץ אותו.

  2. עוברים לספרייה שמכילה את הקוד לדוגמה.

       cd java-docs-samples/flexible/java-17/micronaut-helloworld
    

הפעלת Hello World במחשב המקומי

כדי להריץ את אפליקציית Hello World במחשב המקומי:

  1. מריצים את הפקודה הבאה:
    java -jar target/micronaut-helloworld-0.1.jar
  2. בדפדפן האינטרנט, מזינים את הכתובת הבאה:

    http://localhost:8080

    אם אתם משתמשים ב-Cloud Shell, בסרגל הכלים לוחצים על תצוגה מקדימה באינטרנט ובוחרים באפשרות תצוגה מקדימה ביציאה 8080.

ההודעה Hello World מאפליקציית הדוגמה מוצגת בדף. בחלון הטרמינל, מקישים על Ctrl+C כדי לצאת משרת האינטרנט.

פריסה והפעלה של Hello World ב-App Engine

כדי לפרוס את האפליקציה בסביבה הגמישה של App Engine:

  1. מריצים את הפקודה הבאה מהספרייה java-17/micronaut-helloworld כדי לפרוס את אפליקציית Hello World:

    mvn clean package appengine:deploy
  2. מפעילים את הדפדפן כדי לראות את האפליקציה בכתובת https://PROJECT_ID.REGION_ID.r.appspot.com

    ‫
    gcloud app browse
    כאשר PROJECT_ID מייצג את מזהה הפרויקט ב- Google Cloud.

הפעם, הדף שמציג את ההודעה Hello World מועבר על ידי שרת אינטרנט שפועל במופע של App Engine.

מזל טוב! פרסתם את האפליקציה הראשונה שלכם ב-App Engine בסביבה הגמישה ב-App Engine!

אם נתקלתם בשגיאות כלשהן במהלך פריסת האפליקציה, כדאי לעיין בטיפים לפתרון בעיות.

בקטעים הבאים מפורט מידע על ניקוי, וגם קישורים לפעולות אפשריות שאפשר לבצע.

הסרת המשאבים

כדי להימנע מחיובים, אתם יכולים למחוק את Google Cloud הפרויקט כדי להפסיק את החיוב על כל המשאבים שנעשה בהם שימוש במסגרת הפרויקט.

  1. במסוף Google Cloud , נכנסים לדף Manage resources.

    כניסה לדף Manage resources

  2. ברשימת הפרויקטים, בוחרים את הפרויקט שרוצים למחוק ולוחצים על Delete.
  3. כדי למחוק את הפרויקט, כותבים את מזהה הפרויקט בתיבת הדו-שיח ולוחצים על Shut down.

המאמרים הבאים

לומדים את כל הפלטפורמה

עכשיו, אחרי שראיתם איך מפתחים ומפעילים אפליקציות App Engine, אתם יכולים לעיין בשאר המאמרים בנושא Google Cloud. כבר מותקן אצלכם Google Cloud CLI, שכולל את הכלים שמאפשרים לכם ליצור אינטראקציה עם מוצרים כמו Cloud SQL, ‏ Cloud Storage,‏ Firestore ועוד.

מידע על סביבה גמישה ב-App Engine

הנה כמה נושאים שיעזרו לכם להמשיך ללמוד על App Engine:

סקר קוד של Hello World

האפליקציה Hello World היא האפליקציה הכי פשוטה שאפשר ליצור ב-App Engine, כי היא מכילה רק שירות אחד, יש לה רק גרסה אחת וכל הקוד שלה נמצא בספריית השורש של האפליקציה. בקטע הזה מוסבר על כל אחד מקובצי האפליקציה.

HelloControllerTest.java

בקובץ HelloControllerTest.java מצוינת תבנית URL שמתארת את המקום שבו האפליקציה תקשיב לבקשות, ותגיב לכל בקשה בהודעה 'Hello World'.

/*
 * Copyright 2023 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.example.appengine;

import static org.junit.Assert.assertEquals;

import io.micronaut.context.ApplicationContext;
import io.micronaut.http.HttpRequest;
import io.micronaut.http.client.HttpClient;
import io.micronaut.runtime.server.EmbeddedServer;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

public class HelloControllerTest {
  private static EmbeddedServer server;
  private static HttpClient client;

  @BeforeClass
  public static void setupServer() {

    server = ApplicationContext.run(EmbeddedServer.class);

    client = server.getApplicationContext().createBean(HttpClient.class, server.getURL());
  }

  @AfterClass
  public static void stopServer() {
    if (client != null) {
      client.stop();
    }
    if (server != null) {
      server.stop();
    }
  }

  @Test
  public void testHelloWorldResponse() {
    String response = client.toBlocking().retrieve(HttpRequest.GET("/"));
    assertEquals("Hello World!", response);
  }
}

app.yaml

בקובץ app.yaml מפורטת התצורה הבאה של האפליקציה:

  • הערך env: flex מציין שהאפליקציה משתמשת בסביבה גמישה ב-App Engine.
  • הגדרה של סביבת זמן הריצה שבה האפליקציה משתמשת.

    runtime: java
    env: flex
    runtime_config:
      operating_system: ubuntu22
      runtime_version: 17
    handlers:
    - url: /.*
      script: this field is required, but ignored
    
    manual_scaling:
      instances: 1
    • מידע נוסף על אופן הפעולה של Java runtime זמין במאמר Java runtime.

    pom.xml

    הפרויקט Hello World כולל גם קובץ pom.xml, שמכיל מידע על הפרויקט, כמו התלויות שלו ויעד הבנייה.

    <?xml version="1.0" encoding="UTF-8"?>
    <!--
      Copyright 2023 Google LLC
      Licensed under the Apache License, Version 2.0 (the "License");
      you may not use this file except in compliance with the License.
      You may obtain a copy of the License at
           http://www.apache.org/licenses/LICENSE-2.0
      Unless required by applicable law or agreed to in writing, software
      distributed under the License is distributed on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      See the License for the specific language governing permissions and
      limitations under the License.
    -->
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
      <modelVersion>4.0.0</modelVersion>
      <groupId>com.example.appengine.flexible</groupId>
      <artifactId>micronaut-helloworld</artifactId>
      <version>0.1</version>
    
      <!--
      The parent pom defines common style checks and testing strategies for our samples.
      Removing or replacing it should not affect the execution of the samples in anyway.
      -->
      <parent>
          <groupId>com.google.cloud.samples</groupId>
          <artifactId>shared-configuration</artifactId>
          <version>1.2.0</version>
      </parent>
    
      <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <exec.mainClass>com.example.appengine.Application</exec.mainClass>
        <maven.compiler.target>11</maven.compiler.target>
        <maven.compiler.source>11</maven.compiler.source>
        <micronaut.version>3.10.10</micronaut.version>
      </properties>
    
      <dependencies>
        <dependency>
          <groupId>io.micronaut</groupId>
          <artifactId>micronaut-inject</artifactId>
          <version>${micronaut.version}</version>
          <scope>compile</scope>
        </dependency>
        <dependency>
          <groupId>io.micronaut</groupId>
          <artifactId>micronaut-validation</artifactId>
          <version>${micronaut.version}</version>
          <scope>compile</scope>
        </dependency>
        <dependency>
          <groupId>io.micronaut</groupId>
          <artifactId>micronaut-runtime</artifactId>
          <version>${micronaut.version}</version>
          <scope>compile</scope>
        </dependency>
        <dependency>
          <groupId>io.micronaut</groupId>
          <artifactId>micronaut-http-client</artifactId>
          <version>${micronaut.version}</version>
          <scope>compile</scope>
        </dependency>
        <dependency>
          <groupId>javax.annotation</groupId>
          <artifactId>javax.annotation-api</artifactId>
          <version>1.3.2</version>
          <scope>compile</scope>
        </dependency>
        <dependency>
          <groupId>io.micronaut</groupId>
          <artifactId>micronaut-http-server-netty</artifactId>
          <version>${micronaut.version}</version>
          <scope>compile</scope>
        </dependency>
        <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <version>4.13.2</version>
          <scope>test</scope>
        </dependency>
      </dependencies>
    
      <build>
        <plugins>
          <plugin>
            <groupId>com.google.cloud.tools</groupId>
            <artifactId>appengine-maven-plugin</artifactId>
            <version>2.8.0</version>
            <configuration>
              <projectId>GCLOUD_CONFIG</projectId>
              <version>micronaut-helloworld</version>
            </configuration>
          </plugin>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-shade-plugin</artifactId>
            <version>3.5.1</version>
            <executions>
              <execution>
                <phase>package</phase>
                <goals>
                  <goal>shade</goal>
                </goals>
                <configuration>
                  <transformers>
                    <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                      <mainClass>${exec.mainClass}</mainClass>
                    </transformer>
                    <transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/>
                  </transformers>
                </configuration>
              </execution>
            </executions>
          </plugin>
          <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>exec-maven-plugin</artifactId>
            <version>3.1.1</version>
            <configuration>
              <executable>java</executable>
              <arguments>
                <argument>-noverify</argument>
                <argument>-XX:TieredStopAtLevel=1</argument>
                <argument>-Dcom.sun.management.jmxremote</argument>
                <argument>-classpath</argument>
                <classpath/>
                <argument>${exec.mainClass}</argument>
              </arguments>
            </configuration>
          </plugin>
          <plugin>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>3.2.5</version>
          </plugin>
    
            <plugin>
              <groupId>org.apache.maven.plugins</groupId>
              <artifactId>maven-compiler-plugin</artifactId>
              <version>3.12.1</version>
              <configuration>
                <encoding>UTF-8</encoding>
                <compilerArgs>
                  <arg>-parameters</arg>
                </compilerArgs>
                <annotationProcessorPaths>
                  <path>
                    <groupId>io.micronaut</groupId>
                    <artifactId>micronaut-inject-java</artifactId>
                    <version>${micronaut.version}</version>
                  </path>
                  <path>
                    <groupId>io.micronaut</groupId>
                    <artifactId>micronaut-validation</artifactId>
                    <version>${micronaut.version}</version>
                  </path>
                </annotationProcessorPaths>
              </configuration>
              <executions>
                <execution>
                  <id>test-compile</id>
                  <goals>
                    <goal>testCompile</goal>
                  </goals>
                  <configuration>
                    <compilerArgs>
                      <arg>-parameters</arg>
                    </compilerArgs>
                    <annotationProcessorPaths>
                      <path>
                        <groupId>io.micronaut</groupId>
                        <artifactId>micronaut-inject-java</artifactId>
                        <version>${micronaut.version}</version>
                      </path>
                      <path>
                        <groupId>io.micronaut</groupId>
                        <artifactId>micronaut-validation</artifactId>
                        <version>${micronaut.version}</version>
                      </path>
                    </annotationProcessorPaths>
                  </configuration>
                </execution>
              </executions>
            </plugin>
          </plugins>
    
      </build>
    </project>