Cloud Run에서 자바 작업 빌드 및 만들기

간단한 Cloud Run 작업을 만든 후 소스에서 배포하여 자동으로 코드를 컨테이너 이미지로 패키징하고, 컨테이너 이미지를 Artifact Registry에 업로드하고, Cloud Run에 배포하는 방법을 알아봅니다. 표시된 언어 외에 다른 언어도 사용할 수 있습니다.

시작하기 전에

  1. Google Cloud 계정에 로그인합니다. Google Cloud를 처음 사용하는 경우 계정을 만들고 Google 제품의 실제 성능을 평가해 보세요. 신규 고객에게는 워크로드를 실행, 테스트, 배포하는 데 사용할 수 있는 $300의 무료 크레딧이 제공됩니다.
  2. Google Cloud Console의 프로젝트 선택기 페이지에서 Google Cloud 프로젝트를 선택하거나 만듭니다.

    프로젝트 선택기로 이동

  3. Google Cloud 프로젝트에 결제가 사용 설정되어 있는지 확인합니다.

  4. Google Cloud CLI를 설치합니다.
  5. gcloud CLI를 초기화하려면 다음 명령어를 실행합니다.

    gcloud init
  6. Google Cloud Console의 프로젝트 선택기 페이지에서 Google Cloud 프로젝트를 선택하거나 만듭니다.

    프로젝트 선택기로 이동

  7. Google Cloud 프로젝트에 결제가 사용 설정되어 있는지 확인합니다.

  8. Google Cloud CLI를 설치합니다.
  9. gcloud CLI를 초기화하려면 다음 명령어를 실행합니다.

    gcloud init

샘플 작업 작성

자바로 작업을 작성하려면 다음 안내를 따르세요.

  1. jobs라는 새 디렉터리를 만들고 이 디렉터리로 이동합니다.

    mkdir jobs
    cd jobs
    
  2. src/main/java/com/example이라는 하위 디렉터리에서 실제 작업 코드에 대한 JobsExample.java 파일을 만듭니다. 다음 샘플 줄을 복사합니다.

    
    package com.example;
    
    abstract class JobsExample {
      // These values are provided automatically by the Cloud Run Jobs runtime.
      private static String CLOUD_RUN_TASK_INDEX =
          System.getenv().getOrDefault("CLOUD_RUN_TASK_INDEX", "0");
      private static String CLOUD_RUN_TASK_ATTEMPT =
          System.getenv().getOrDefault("CLOUD_RUN_TASK_ATTEMPT", "0");
    
      // User-provided environment variables
      private static int SLEEP_MS = Integer.parseInt(System.getenv().getOrDefault("SLEEP_MS", "0"));
      private static float FAIL_RATE =
          Float.parseFloat(System.getenv().getOrDefault("FAIL_RATE", "0.0"));
    
      // Start script
      public static void main(String[] args) {
        System.out.println(
            String.format(
                "Starting Task #%s, Attempt #%s...", CLOUD_RUN_TASK_INDEX, CLOUD_RUN_TASK_ATTEMPT));
        try {
          runTask(SLEEP_MS, FAIL_RATE);
        } catch (RuntimeException | InterruptedException e) {
          System.err.println(
              String.format(
                  "Task #%s, Attempt #%s failed.", CLOUD_RUN_TASK_INDEX, CLOUD_RUN_TASK_ATTEMPT));
          // Catch error and denote process-level failure to retry Task
          System.exit(1);
        }
      }
    
      static void runTask(int sleepTime, float failureRate) throws InterruptedException {
        // Simulate work
        if (sleepTime > 0) {
          Thread.sleep(sleepTime);
        }
    
        // Simulate errors
        if (failureRate < 0 || failureRate > 1) {
          System.err.println(
              String.format(
                  "Invalid FAIL_RATE value: %s. Must be a float between 0 and 1 inclusive.",
                  failureRate));
          return;
        }
        if (Math.random() < failureRate) {
          throw new RuntimeException("Task Failed.");
        }
        System.out.println(String.format("Completed Task #%s", CLOUD_RUN_TASK_INDEX));
      }
    }

    Cloud Run 작업을 사용하면 작업이 실행될 태스크의 수를 지정할 수 있습니다. 이 샘플 코드에서는 기본 제공 CLOUD_RUN_TASK_INDEX 환경 변수를 사용하는 방법을 보여줍니다. 각 태스크는 실행 중인 컨테이너의 복사본 하나를 나타냅니다. 태스크는 일반적으로 병렬로 실행됩니다. 각 태스크에서 데이터 하위 집합을 독립적으로 처리할 수 있는 경우 여러 태스크를 사용하는 것이 유용합니다.

    각 태스크는 CLOUD_RUN_TASK_INDEX 환경 변수에 저장된 색인을 인식합니다. 기본 제공 CLOUD_RUN_TASK_COUNT 환경 변수에는 작업 실행 시 --tasks 매개변수를 통해 제공되는 태스크 수가 포함됩니다.

    또한 표시된 코드는 기본 제공 CLOUD_RUN_TASK_ATTEMPT 환경 변수를 사용하여 태스크를 재시도하는 방법을 보여줍니다. 이 환경 변수에는 처음 시도할 때 0부터 시작하여 연속으로 재시도할 때마다 1씩 증가하여 --max-retries까지 이 태스크를 재시도한 횟수가 포함됩니다.

    또한 코드를 사용하면 재시도를 테스트하기 위한 방법으로 오류를 생성하고 오류 로그를 생성하여 어떻게 표시되는지 확인할 수 있습니다.

  3. 다음 콘텐츠로 pom.xml이라는 파일을 만듭니다.

    <?xml version="1.0" encoding="UTF-8"?>
    <!--
    Copyright 2021 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.run</groupId>
      <artifactId>jobs-example</artifactId>
      <version>0.0.1</version>
      <packaging>jar</packaging>
    
      <!--  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>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <maven.compiler.target>17</maven.compiler.target>
        <maven.compiler.source>17</maven.compiler.source>
      </properties>
    
      <dependencyManagement>
        <dependencies>
          <dependency>
            <artifactId>libraries-bom</artifactId>
            <groupId>com.google.cloud</groupId>
            <scope>import</scope>
            <type>pom</type>
            <version>26.32.0</version>
          </dependency>
        </dependencies>
      </dependencyManagement>
    
      <dependencies>
        <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <version>4.13.2</version>
          <scope>test</scope>
        </dependency>
        <dependency>
          <groupId>com.google.truth</groupId>
          <artifactId>truth</artifactId>
          <version>1.4.0</version>
          <scope>test</scope>
        </dependency>
        <dependency>
          <groupId>com.google.cloud</groupId>
          <artifactId>google-cloud-logging</artifactId>
          <scope>test</scope>
        </dependency>
      </dependencies>
    
      <build>
        <plugins>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-jar-plugin</artifactId>
            <version>3.3.0</version>
            <configuration>
              <archive>
                <manifest>
                  <addClasspath>true</addClasspath>
                  <mainClass>com.example.JobsExample</mainClass>
                </manifest>
              </archive>
            </configuration>
          </plugin>
        </plugins>
      </build>
    </project>
    
  4. Buildpack에서 지원하는 Java 버전으로 빌드하려면 다음 콘텐츠로 project.toml 파일을 만듭니다.

    # Default version is Java 11
    #  - See https://cloud.google.com/docs/buildpacks/java#specify_a_java_version
    # Match the version required in pom.xml by setting it here
    #  - See https://cloud.google.com/docs/buildpacks/set-environment-variables#build_the_application_with_environment_variables
    
    [[build.env]]
      name = "GOOGLE_RUNTIME_VERSION"
      value = "17"
    

코드가 완료되었으며 컨테이너에 패키징될 수 있습니다.

작업 컨테이너를 빌드하여 Artifact Registry로 전송하고 Cloud Run에 배포

중요: 이 빠른 시작에서는 빠른 시작에 사용 중인 프로젝트에 소유자 역할이나 편집자 역할이 있다고 가정합니다. 그렇지 않은 경우 필요한 권한은 Cloud Run 배포 권한, Cloud Build 권한, Artifact Registry 권한을 참조하세요.

이 빠른 시작에서는 소스에서 배포를 사용하여 컨테이너를 빌드하고, Artifact Registry에 업로드하고, Cloud Run에 작업을 배포합니다.

gcloud run jobs deploy job-quickstart \
    --source . \
    --tasks 50 \
    --set-env-vars SLEEP_MS=10000 \
    --set-env-vars FAIL_RATE=0.1 \
    --max-retries 5 \
    --region REGION \
    --project=PROJECT_ID

여기서 PROJECT_ID는 프로젝트 ID이고 REGION은 리전입니다(예: us-central1). 다양한 매개변수를 테스트 목적으로 사용할 값으로 변경할 수 있습니다. SLEEP_MS는 작업을 시뮬레이션하고 FAIL_RATE로 인해 태스크의 X%가 실패하므로 동시 로드를 사용하여 실패한 태스크를 재시도할 수 있습니다.

Cloud Run에서 작업 실행

방금 만든 작업을 실행하려면 다음 명령어를 실행합니다.

gcloud run jobs execute job-quickstart --region REGION

REGION을 작업을 만들고 배포할 때 사용한 리전으로 바꿉니다(예: us-central1).

다음 단계

코드 소스에서 컨테이너를 빌드하고 저장소로 푸시하는 방법에 대한 자세한 내용은 다음을 참조하세요.