使用 Java (第 1 代) 建立及部署 HTTP Cloud Run 函式

本指南將逐步說明如何使用 Java 執行階段編寫 Cloud Run 函式。Cloud Run 函式分為兩種類型:

  • HTTP 函式,可從標準 HTTP 要求叫用。
  • 事件驅動函式,用於處理 Cloud 基礎架構中的事件,例如 Pub/Sub 主題上的訊息,或 Cloud Storage 值區中的變更。

本文說明如何建立簡單的 HTTP 函式,並使用 MavenGradle 建構函式。

事前準備

  1. Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  3. Make sure that billing is enabled for your Google Cloud project.

  4. Enable the Cloud Functions and Cloud Build APIs.

    Enable the APIs

  5. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  6. Make sure that billing is enabled for your Google Cloud project.

  7. Enable the Cloud Functions and Cloud Build APIs.

    Enable the APIs

  8. 安裝並初始化 Google Cloud SDK
  9. 更新並安裝 gcloud 元件:
    gcloud components update
  10. 準備開發環境。

    前往 Java 設定指南

  11. 建立函式

    本節說明如何建立函式。

    Maven

    1. 在本機系統上為函式程式碼建立目錄:

      Linux 或 Mac OS X:

       mkdir ~/helloworld
       cd ~/helloworld
      

      Windows:

       mkdir %HOMEPATH%\helloworld
       cd %HOMEPATH%\helloworld
      
    2. 建立專案結構,內含來源目錄和來源檔案。

      mkdir -p src/main/java/functions
      touch src/main/java/functions/HelloWorld.java
      
    3. 將下列內容新增至 HelloWorld.java 檔案:

      
      package functions;
      
      import com.google.cloud.functions.HttpFunction;
      import com.google.cloud.functions.HttpRequest;
      import com.google.cloud.functions.HttpResponse;
      import java.io.BufferedWriter;
      import java.io.IOException;
      
      public class HelloWorld implements HttpFunction {
        // Simple function to return "Hello World"
        @Override
        public void service(HttpRequest request, HttpResponse response)
            throws IOException {
          BufferedWriter writer = response.getWriter();
          writer.write("Hello World!");
        }
      }

      這個範例函式會輸出問候語「Hello World!」。

    Gradle

    1. 在本機系統上為函式程式碼建立目錄:

      Linux 或 Mac OS X:

       mkdir ~/helloworld-gradle
       cd ~/helloworld-gradle
      

      Windows:

       mkdir %HOMEPATH%\helloworld-gradle
       cd %HOMEPATH%\helloworld-gradle
      
    2. 建立專案結構,內含來源目錄和來源檔案。

       mkdir -p src/main/java/functions
       touch src/main/java/functions/HelloWorld.java
      
    3. 將下列內容新增至 HelloWorld.java 檔案:

      
      package functions;
      
      import com.google.cloud.functions.HttpFunction;
      import com.google.cloud.functions.HttpRequest;
      import com.google.cloud.functions.HttpResponse;
      import java.io.BufferedWriter;
      import java.io.IOException;
      
      public class HelloWorld implements HttpFunction {
        // Simple function to return "Hello World"
        @Override
        public void service(HttpRequest request, HttpResponse response)
            throws IOException {
          BufferedWriter writer = response.getWriter();
          writer.write("Hello World!");
        }
      }

      這個範例函式會輸出問候語「Hello World!」。

    指定依附元件

    下一步是設定依附元件:

    Maven

    將目錄變更為您在上方建立的 helloworld 目錄,然後建立 pom.xml 檔案:

     cd ~/helloworld
     touch pom.xml
    

    如要使用 Maven 管理依附元件,請在專案的 pom.xml 檔案中,指定 <dependencies> 區段內的依附元件。在本練習中,請將下列內容複製到 pom.xml 檔案。

    <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.functions</groupId>
      <artifactId>functions-hello-world</artifactId>
      <version>1.0.0-SNAPSHOT</version>
      <properties>
        <maven.compiler.target>11</maven.compiler.target>
        <maven.compiler.source>11</maven.compiler.source>
      </properties>
    
      <dependencies>
        <!-- Required for Function primitives -->
        <dependency>
          <groupId>com.google.cloud.functions</groupId>
          <artifactId>functions-framework-api</artifactId>
          <version>1.1.0</version>
          <scope>provided</scope>
        </dependency>
      </dependencies>
    
      <build>
        <plugins>
          <plugin>
            <!--
              Google Cloud Functions Framework Maven plugin
    
              This plugin allows you to run Cloud Functions Java code
              locally. Use the following terminal command to run a
              given function locally:
    
              mvn function:run -Drun.functionTarget=your.package.yourFunction
            -->
            <groupId>com.google.cloud.functions</groupId>
            <artifactId>function-maven-plugin</artifactId>
            <version>0.11.0</version>
            <configuration>
              <functionTarget>functions.HelloWorld</functionTarget>
            </configuration>
          </plugin>
        </plugins>
      </build>
    </project>

    如需以 Maven 為基礎的完整範例,請參閱 helloworld

    Gradle

    將目錄變更為您在上方建立的 helloworld-gradle 目錄,然後建立 build.gradle 檔案:

     cd ~/helloworld-gradle
     touch build.gradle
    

    如要使用 Gradle 管理依附元件,請在專案的 build.gradle 檔案中指定依附元件。在本練習中,請將下列內容複製到 build.gradle 檔案。請注意,這個 build.gradle 檔案包含自訂工作,可協助您在本機執行函式。

    apply plugin: 'java'
    
    repositories {
      jcenter()
      mavenCentral()
    }
    configurations {
        invoker
    }
    
    dependencies {
      // Every function needs this dependency to get the Functions Framework API.
      compileOnly 'com.google.cloud.functions:functions-framework-api:1.1.0'
    
      // To run function locally using Functions Framework's local invoker
      invoker 'com.google.cloud.functions.invoker:java-function-invoker:1.3.1'
    
      // These dependencies are only used by the tests.
      testImplementation 'com.google.cloud.functions:functions-framework-api:1.1.0'
      testImplementation 'junit:junit:4.13.2'
      testImplementation 'com.google.truth:truth:1.4.0'
      testImplementation 'org.mockito:mockito-core:5.10.0'
    
    }
    
    // Register a "runFunction" task to run the function locally
    tasks.register("runFunction", JavaExec) {
      main = 'com.google.cloud.functions.invoker.runner.Invoker'
      classpath(configurations.invoker)
      inputs.files(configurations.runtimeClasspath, sourceSets.main.output)
      args(
        '--target', project.findProperty('run.functionTarget') ?: '',
        '--port', project.findProperty('run.port') ?: 8080
      )
      doFirst {
        args('--classpath', files(configurations.runtimeClasspath, sourceSets.main.output).asPath)
      }
    }

    如需以 Gradle 為基礎的完整範例,請參閱 helloworld-gradle

    在本機建構及測試

    部署函式前,您可以在本機建構及測試函式:

    Maven

    執行下列指令,確認函式是否已建構完成:

    mvn compile
    

    您也可以使用 mvn package 指令編譯 Java 程式碼、執行任何測試,然後將程式碼封裝在目標目錄中的 JAR 檔案內。如要進一步瞭解 Maven 建構生命週期,請參閱這篇文章

    如要測試函式,請執行下列指令:

    mvn function:run
    

    Gradle

    執行下列指令,確認函式是否已建構完成:

    gradle build
    

    如要測試函式,請執行下列指令:

    gradle runFunction -Prun.functionTarget=functions.HelloWorld
    

    如果測試順利完成,系統會顯示網址,您可以在網路瀏覽器中造訪該網址,查看函式運作情形: http://localhost:8080/。畫面上應會顯示 Hello World! 訊息。

    或者,您也可以透過其他終端機視窗使用 curl,傳送要求至此函式:

    curl localhost:8080
    # Output: Hello World!
    

    部署函式

    Maven

    如要使用 HTTP 觸發條件部署函式,請在 helloworld 目錄中執行下列指令:

    gcloud functions deploy my-first-function --no-gen2 --entry-point functions.HelloWorld --runtime java17 --trigger-http --memory 512MB --allow-unauthenticated
    其中 my-first-function 是註冊名稱,函式會透過這個名稱在 Google Cloud 控制台中識別,而 --entry-point 則指定函式的完整類別名稱 (FQN)。

    Gradle

    如要使用 HTTP 觸發條件部署函式,請在 helloworld-gradle 目錄中執行下列指令:

    gcloud functions deploy my-first-function --no-gen2 --entry-point functions.HelloWorld --runtime java17 --trigger-http --memory 512MB --allow-unauthenticated
    其中 my-first-function 是註冊名稱,函式會透過這個名稱在 Google Cloud 控制台中識別,而 --entry-point 則指定函式的完整類別名稱 (FQN)。

    測試已部署的函式

    1. 函式完成部署時,請記下 httpsTrigger.url 屬性,或使用下列指令找到這個屬性:

      gcloud functions describe my-first-function
      內容應該會類似這樣:

      https://GCP_REGION-PROJECT_ID.cloudfunctions.net/my-first-function
    2. 透過您的瀏覽器造訪這個網址。畫面上應會顯示 Hello World! 訊息。

    查看記錄

    您可以使用 Google Cloud CLI,以及在 Cloud Logging UI 中查看 Cloud Run functions 的記錄。

    使用指令列工具

    如要透過 gcloud CLI 查看函式的記錄檔,請使用 logs read 指令加上函式的名稱:

    gcloud functions logs read my-first-function

    輸出應會如下所示:

    LEVEL  NAME               EXECUTION_ID  TIME_UTC                 LOG
    D      my-first-function  k2bqgroszo4u  2020-07-24 18:18:01.791  Function execution started
    D      my-first-function  k2bqgroszo4u  2020-07-24 18:18:01.958  Function execution took 168 ms, finished with status code: 200
    ...

    使用記錄資訊主頁

    您也可以從Google Cloud 控制台查看 Cloud Run functions 的記錄。