App Engine フレキシブル環境で Java アプリを作成する

リージョン ID

REGION_ID は、アプリの作成時に選択したリージョンに基づいて Google が割り当てる省略形のコードです。一部のリージョン ID は、一般的に使用されている国や州のコードと類似しているように見える場合がありますが、このコードは国または州に対応するものではありません。2020 年 2 月以降に作成されたアプリの場合、REGION_ID.r は App Engine の URL に含まれています。この日付より前に作成されたアプリの場合、URL のリージョン ID は省略可能です。

詳しくは、リージョン ID をご覧ください。

このクイックスタートでは、ショート メッセージを表示するアプリを作成してデプロイする方法を説明します。サンプル アプリケーションでは Java バージョン 17 が使用されます。

Java バージョン 8バージョン 11 のコードサンプルは GitHub で入手できます。

始める前に

このクイックスタートでは、ローカルマシンに Java SE 17 Development Kit(JDK)がインストール済みであることを前提としています。
  1. Google Cloud アカウントにログインします。Google Cloud を初めて使用する場合は、アカウントを作成して、実際のシナリオでの Google プロダクトのパフォーマンスを評価してください。新規のお客様には、ワークロードの実行、テスト、デプロイができる無料クレジット $300 分を差し上げます。
  2. Google Cloud Console の [プロジェクト セレクタ] ページで、Google Cloud プロジェクトを選択または作成します。

    プロジェクト セレクタに移動

  3. Google Cloud プロジェクトで課金が有効になっていることを確認します

  4. Cloud Build API を有効にします。

    API を有効にする

  5. Google Cloud CLI をインストールします。
  6. gcloud CLI を初期化するには:

    gcloud init
  7. Google Cloud Console の [プロジェクト セレクタ] ページで、Google Cloud プロジェクトを選択または作成します。

    プロジェクト セレクタに移動

  8. Google Cloud プロジェクトで課金が有効になっていることを確認します

  9. Cloud Build API を有効にします。

    API を有効にする

  10. Google Cloud CLI をインストールします。
  11. gcloud CLI を初期化するには:

    gcloud init

追加の前提条件

  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 アプリをダウンロードする

App Engine 用のシンプルな Hello World アプリが用意されており、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 プロジェクト ID です。

今回、Hello World メッセージが表示されるページは、App Engine インスタンスで実行されているウェブサーバーから配信されます。

これで完了です。App Engine フレキシブル環境に最初の App Engine アプリケーションをデプロイしました。

アプリケーションのデプロイでエラーが発生した場合は、トラブルシューティングのヒントをご覧ください。

クリーンアップの詳細については、以下の説明をご覧ください。また、活用できる次のステップへのリンクも併せてご確認ください。

クリーンアップ

課金されないようにするには、Google Cloud プロジェクトを削除してプロジェクト内のすべてのリソースへの課金を停止します。

  1. Google Cloud コンソールで、[リソースの管理] ページに移動します。

    [リソースの管理] に移動

  2. プロジェクト リストで、削除するプロジェクトを選択し、[削除] をクリックします。
  3. ダイアログでプロジェクト ID を入力し、[シャットダウン] をクリックしてプロジェクトを削除します。

次のステップ

プラットフォーム全体について学習する

App Engine アプリの開発とデプロイについて概要を理解した後は、Google Cloud の残りの部分についても確認します。すでに Google Cloud CLI がインストールされているため、Cloud SQL、Cloud Storage、Firestore などのプロダクトを操作するツールを使用できます。

App Engine フレキシブル環境について学習する

App Engine についてさらに理解を深めるためのトピックをご紹介します。

Hello World コードレビュー

Hello World は、サービスが 1 つだけ含まれ、バージョンも 1 つだけで、すべてのコードがアプリケーションのルート ディレクトリにあるという、最もシンプルな 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 ランタイムの動作の詳細については、Java ランタイムをご覧ください。

    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.3</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>