App Engine 가변형 환경에서 자바 앱 만들기

리전 ID

REGION_ID는 앱을 만들 때 선택한 리전을 기준으로 Google에서 할당하는 축약된 코드입니다. 일부 리전 ID는 일반적으로 사용되는 국가 및 주/도 코드와 비슷하게 표시될 수 있지만 코드는 국가 또는 주/도와 일치하지 않습니다. 2020년 2월 이후에 생성된 앱의 경우 REGION_ID.r이 App Engine URL에 포함됩니다. 이 날짜 이전에 만든 기존 앱의 경우 URL에서 리전 ID는 선택사항입니다.

리전 ID에 대해 자세히 알아보세요.

이 빠른 시작에서는 짧은 메시지를 표시하는 앱을 만들고 배포하는 방법을 보여줍니다. 샘플 애플리케이션은 자바 버전 17을 사용합니다.

GitHub에서 자바 버전 8버전 11용 코드 샘플을 사용할 수 있습니다.

시작하기 전에

이 빠른 시작에서는 로컬 머신에 자바 SE 17 개발 키트(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 키를 눌러 웹 서버를 종료합니다.

App Engine에서 Hello World 배포 및 실행

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를 나타냅니다.

이 경우, App Engine 인스턴스에서 실행 중인 웹 서버가 Hello World 메시지가 표시된 페이지를 제공합니다.

수고하셨습니다. 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는 가장 간단한 App Engine 앱으로, 한 가지 서비스만을 포함하고 버전도 하나뿐이며 모든 코드가 앱의 루트 디렉터리에 있습니다. 이 섹션은 각 앱 파일을 자세히 설명합니다.

HelloControllerTest.java

HelloControllerTest.java 파일에서는 앱이 요청을 리슨하고 'Hello World' 메시지로 요청에 응답하는 위치를 설명하는 URL 패턴을 지정합니다.

/*
 * 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
    • 자바 런타임이 작동하는 방식에 대한 자세한 내용은 자바 런타임을 참조하세요.

    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>
    
    • pom.xml 파일에 대한 자세한 내용은 Maven 문서를 참조하세요.