使用 Google Cloud CLI 创建第 1 代 Cloud Functions 函数

本页面介绍如何使用 Google Cloud CLI 创建和部署第 1 代 Cloud Functions 函数。

准备工作

  1. 登录您的 Google Cloud 账号。如果您是 Google Cloud 新手,请创建一个账号来评估我们的产品在实际场景中的表现。新客户还可获享 $300 赠金,用于运行、测试和部署工作负载。
  2. 在 Google Cloud Console 中的项目选择器页面上,选择或创建一个 Google Cloud 项目

    转到“项目选择器”

  3. 确保您的 Google Cloud 项目已启用结算功能

  4. 启用 Cloud Functions and Cloud Build API。

    启用 API

  5. 在 Google Cloud Console 中的项目选择器页面上,选择或创建一个 Google Cloud 项目

    转到“项目选择器”

  6. 确保您的 Google Cloud 项目已启用结算功能

  7. 启用 Cloud Functions and Cloud Build API。

    启用 API

  8. 安装并初始化 gcloud CLI
  9. 更新 gcloud 组件:
    gcloud components update
  10. 需要命令提示符吗?您可以使用 Google Cloud Shell。Google Cloud Shell 命令行环境已经包含 Google Cloud CLI,因此您无需再进行安装。Google Compute Engine 虚拟机也预装了 Google Cloud CLI。

  11. 准备开发环境。

获取示例代码

  1. 将示例代码库克隆到您的本地机器:

    Node.js

    git clone https://github.com/GoogleCloudPlatform/nodejs-docs-samples.git

    或者,您也可以下载该示例的 zip 文件并将其解压缩。

    Python

    git clone https://github.com/GoogleCloudPlatform/python-docs-samples.git

    或者,您也可以下载该示例的 zip 文件并将其解压缩。

    Go

    git clone https://github.com/GoogleCloudPlatform/golang-samples.git

    或者,您也可以下载该示例的 zip 文件并将其解压缩。

    Java

    git clone https://github.com/GoogleCloudPlatform/java-docs-samples.git

    或者,您也可以下载该示例的 zip 文件并将其解压缩。

    C#

    git clone https://github.com/GoogleCloudPlatform/dotnet-docs-samples.git

    或者,您也可以下载该示例的 zip 文件并将其解压缩。

    Ruby

    git clone https://github.com/GoogleCloudPlatform/ruby-docs-samples.git

    或者,您也可以下载该示例的 zip 文件并将其解压缩。

    PHP

    git clone https://github.com/GoogleCloudPlatform/php-docs-samples.git

    或者,您也可以下载该示例的 zip 文件并将其解压缩。

  2. 切换到包含 Cloud Functions 函数示例代码的目录:

    Node.js

    cd nodejs-docs-samples/functions/helloworld/

    Python

    cd python-docs-samples/functions/helloworld/

    Go

    cd golang-samples/functions/helloworld/

    Java

    cd java-docs-samples/functions/helloworld/helloworld/

    C#

    cd dotnet-docs-samples/functions/helloworld/HelloWorld/

    Ruby

    cd ruby-docs-samples/functions/helloworld/get/

    PHP

    cd php-docs-samples/functions/helloworld_get/

  3. 查看示例代码:

    Node.js

    const functions = require('@google-cloud/functions-framework');
    
    // Register an HTTP function with the Functions Framework that will be executed
    // when you make an HTTP request to the deployed function's endpoint.
    functions.http('helloGET', (req, res) => {
      res.send('Hello World!');
    });

    Python

    import functions_framework
    @functions_framework.http
    def hello_get(request):
        """HTTP Cloud Function.
        Args:
            request (flask.Request): The request object.
            <https://flask.palletsprojects.com/en/1.1.x/api/#incoming-request-data>
        Returns:
            The response text, or any set of values that can be turned into a
            Response object using `make_response`
            <https://flask.palletsprojects.com/en/1.1.x/api/#flask.make_response>.
        Note:
            For more information on how Flask integrates with Cloud
            Functions, see the `Writing HTTP functions` page.
            <https://cloud.google.com/functions/docs/writing/http#http_frameworks>
        """
        return "Hello World!"
    
    

    Go

    
    // Package helloworld provides a set of Cloud Functions samples.
    package helloworld
    
    import (
    	"fmt"
    	"net/http"
    )
    
    // HelloGet is an HTTP Cloud Function.
    func HelloGet(w http.ResponseWriter, r *http.Request) {
    	fmt.Fprint(w, "Hello, World!")
    }
    

    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!");
      }
    }

    C#

    using Google.Cloud.Functions.Framework;
    using Microsoft.AspNetCore.Http;
    using System.Threading.Tasks;
    
    namespace HelloWorld;
    
    public class Function : IHttpFunction
    {
        public async Task HandleAsync(HttpContext context)
        {
            await context.Response.WriteAsync("Hello World!");
        }
    }

    Ruby

    require "functions_framework"
    
    FunctionsFramework.http "hello_get" do |_request|
      # The request parameter is a Rack::Request object.
      # See https://www.rubydoc.info/gems/rack/Rack/Request
    
      # Return the response body as a string.
      # You can also return a Rack::Response object, a Rack response array, or
      # a hash which will be JSON-encoded into a response.
      "Hello World!"
    end

    PHP

    
    use Psr\Http\Message\ServerRequestInterface;
    
    function helloGet(ServerRequestInterface $request): string
    {
        return 'Hello, World!' . PHP_EOL;
    }
    

部署函数

如需使用 HTTP 触发器部署函数,请在包含您的函数的目录中运行以下命令:

Node.js

gcloud functions deploy helloGET \
--runtime nodejs20 --trigger-http

使用 --runtime 标志可以指定支持的 Node.js 版本的运行时 ID 来运行您的函数。

Python

gcloud functions deploy hello_get \
--runtime python312 --trigger-http

使用 --runtime 标志可以指定支持的 Python 版本的运行时 ID 来运行您的函数。

Go

gcloud functions deploy HelloGet \
--runtime go121 --trigger-http

使用 --runtime 标志可以指定支持的 Go 版本的运行时 ID 来运行您的函数。

Java

gcloud functions deploy java-helloworld \
--entry-point functions.HelloWorld \
--runtime java17 \
--memory 512MB --trigger-http

使用 --runtime 标志可以指定支持的 Java 版本的运行时 ID 来运行您的函数。

C#

gcloud functions deploy csharp-helloworld \
--entry-point HelloWorld.Function \
--runtime dotnet6 --trigger-http

使用 --runtime 标志可以指定支持的 .NET 版本的运行时 ID 来运行您的函数。

Ruby

gcloud functions deploy hello_get --runtime ruby32 --trigger-http

使用 --runtime 标志可以指定支持的 Ruby 版本的运行时 ID 来运行您的函数。

PHP

 gcloud functions deploy helloGet --runtime php82 --trigger-http

使用 --runtime 标志可以指定支持的 PHP 版本的运行时 ID 来运行您的函数。

您可以视情况使用 --allow-unauthenticated 标志在不进行身份验证的情况下访问函数。这对于测试非常有用,但除非您创建公共 API 或网站,否则我们不建议在生产环境中使用此设置。此外,根据您的公司政策设置,此选项可能不适合您。如需详细了解如何调用需要进行身份验证的函数,请参阅进行身份验证以便调用

测试函数

  1. 当函数完成部署时,请记下 httpsTriggerurl 属性,或使用以下命令查找该属性:

    Node.js

    gcloud functions describe helloGET

    Python

    gcloud functions describe hello_get

    Go

    gcloud functions describe HelloGet

    Java

    gcloud functions describe java-helloworld

    C#

    gcloud functions describe csharp-helloworld

    Ruby

    gcloud functions describe hello_get

    PHP

    gcloud functions describe helloGet

    该属性应如下所示:

    Node.js

    https://GCP_REGION-PROJECT_ID.cloudfunctions.net/helloGET

    Python

    https://GCP_REGION-PROJECT_ID.cloudfunctions.net/hello_get

    Go

    https://GCP_REGION-PROJECT_ID.cloudfunctions.net/HelloGet

    Java

    https://GCP_REGION-PROJECT_ID.cloudfunctions.net/java-helloworld

    C#

    https://GCP_REGION-PROJECT_ID.cloudfunctions.net/csharp-helloworld

    Ruby

    https://GCP_REGION-PROJECT_ID.cloudfunctions.net/hello_get

    PHP

    https://GCP_REGION-PROJECT_ID.cloudfunctions.net/helloGet

  2. 在浏览器中访问此网址。您应该会看到 Hello World! 消息。

删除函数

如需删除函数,请运行以下命令:

Node.js

gcloud functions delete helloGET 

Python

gcloud functions delete hello_get 

Go

gcloud functions delete HelloGet 

Java

gcloud functions delete java-helloworld 

C#

gcloud functions delete csharp-helloworld 

Ruby

gcloud functions delete hello_get 

PHP

gcloud functions delete helloGet 

后续步骤

请参阅所选运行时版本的“您的第一个函数”指南,了解如何设置开发环境、从头开始创建新函数、指定依赖项、部署函数、测试函数以及查看日志。请注意,以下指南仅适用于 Cloud Functions(第 1 代):