使用 Java 创建和部署 HTTP Cloud Run functions 函数(第 1 代)

本指南将引导您完成用 Java 运行时编写 Cloud Functions 函数的过程。Cloud Run functions 函数有两种类型:

  • HTTP 函数,通过标准 HTTP 请求调用。
  • 事件驱动函数,用于处理来自云基础设施的事件,例如 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. Verify 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. Verify 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 界面查看 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
    ...

    使用 Logging 信息中心

    您还可以通过 Google Cloud 控制台查看 Cloud Run functions 的日志。