Cloud Storage 教程(第 2 代)


本简易教程演示了如何使用 Cloud Storage 触发器编写、部署和触发 Cloud Functions 事件驱动函数来响应 Cloud Storage 事件。

如果您要查找使用 Cloud Storage 本身的代码示例,请访问 Google Cloud 示例浏览器

目标

费用

在本文档中,您将使用 Google Cloud 的以下收费组件:

  • Cloud Functions
  • Cloud Build
  • Pub/Sub
  • Cloud Storage
  • Artifact Registry
  • Eventarc
  • Cloud Logging

如需了解详情,请参阅 Cloud Functions 价格

您可使用价格计算器根据您的预计使用情况来估算费用。 Google Cloud 新用户可能有资格申请免费试用


如需直接在 Cloud Shell Editor 中按照此任务的分步指南来执行操作,请点击操作演示

操作演示


准备工作

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

    转到“项目选择器”

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

  4. 启用 Cloud Functions, Cloud Build, Artifact Registry, Eventarc, Logging, and Pub/Sub API。

    启用 API

  5. 安装 Google Cloud CLI。
  6. 如需初始化 gcloud CLI,请运行以下命令:

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

    转到“项目选择器”

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

  9. 启用 Cloud Functions, Cloud Build, Artifact Registry, Eventarc, Logging, and Pub/Sub API。

    启用 API

  10. 安装 Google Cloud CLI。
  11. 如需初始化 gcloud CLI,请运行以下命令:

    gcloud init
  12. 如果您已经安装 gcloud CLI,请运行以下命令进行更新:

    gcloud components update
  13. 准备开发环境:

前提条件

  1. 创建一个区域级存储桶,其中 YOUR_BUCKET_NAME 是全局唯一的存储桶名称,REGION 是您计划在其中部署函数的区域:

    gsutil mb -l REGION gs://YOUR_BUCKET_NAME
    
  2. 要使用 Cloud Storage 函数,请将 pubsub.publisher 角色授予 Cloud Storage 服务账号:

    PROJECT_ID=$(gcloud config get-value project)
    PROJECT_NUMBER=$(gcloud projects list --filter="project_id:$PROJECT_ID" --format='value(project_number)')
    
    SERVICE_ACCOUNT=$(gsutil kms serviceaccount -p $PROJECT_NUMBER)
    
    gcloud projects add-iam-policy-binding $PROJECT_ID \
      --member serviceAccount:$SERVICE_ACCOUNT \
      --role roles/pubsub.publisher
    

准备应用

  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/v2/helloGCS/

    Python

    cd python-docs-samples/functions/v2/storage/

    Go

    cd golang-samples/functions/functionsv2/hellostorage/

    Java

    cd java-docs-samples/functions/v2/hello-gcs/

    C#

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

    Ruby

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

    PHP

    cd php-docs-samples/functions/helloworld_storage/

部署并触发函数

Cloud Storage 函数基于 Cloud Storage 发出的 Pub/Sub 通知,并且支持类似事件类型:

以下部分介绍如何为每种类型的事件部署和触发函数。

完成对象创建

Cloud Storage 对象的“写入”成功完成后,“完成对象创建”事件会被触发。具体而言,这意味着创建新对象或覆盖现有对象会触发此事件。此触发器会忽略归档操作和元数据更新操作。

完成对象创建:部署函数

查看处理 Cloud Storage 事件的示例函数:

Node.js

const functions = require('@google-cloud/functions-framework');

// Register a CloudEvent callback with the Functions Framework that will
// be triggered by Cloud Storage.
functions.cloudEvent('helloGCS', cloudEvent => {
  console.log(`Event ID: ${cloudEvent.id}`);
  console.log(`Event Type: ${cloudEvent.type}`);

  const file = cloudEvent.data;
  console.log(`Bucket: ${file.bucket}`);
  console.log(`File: ${file.name}`);
  console.log(`Metageneration: ${file.metageneration}`);
  console.log(`Created: ${file.timeCreated}`);
  console.log(`Updated: ${file.updated}`);
});

Python

from cloudevents.http import CloudEvent

import functions_framework

# Triggered by a change in a storage bucket
@functions_framework.cloud_event
def hello_gcs(cloud_event: CloudEvent) -> tuple:
    """This function is triggered by a change in a storage bucket.

    Args:
        cloud_event: The CloudEvent that triggered this function.
    Returns:
        The event ID, event type, bucket, name, metageneration, and timeCreated.
    """
    data = cloud_event.data

    event_id = cloud_event["id"]
    event_type = cloud_event["type"]

    bucket = data["bucket"]
    name = data["name"]
    metageneration = data["metageneration"]
    timeCreated = data["timeCreated"]
    updated = data["updated"]

    print(f"Event ID: {event_id}")
    print(f"Event type: {event_type}")
    print(f"Bucket: {bucket}")
    print(f"File: {name}")
    print(f"Metageneration: {metageneration}")
    print(f"Created: {timeCreated}")
    print(f"Updated: {updated}")

    return event_id, event_type, bucket, name, metageneration, timeCreated, updated

Go


// Package helloworld provides a set of Cloud Functions samples.
package helloworld

import (
	"context"
	"fmt"
	"log"

	"github.com/GoogleCloudPlatform/functions-framework-go/functions"
	"github.com/cloudevents/sdk-go/v2/event"
	"github.com/googleapis/google-cloudevents-go/cloud/storagedata"
	"google.golang.org/protobuf/encoding/protojson"
)

func init() {
	functions.CloudEvent("HelloStorage", helloStorage)
}

// helloStorage consumes a CloudEvent message and logs details about the changed object.
func helloStorage(ctx context.Context, e event.Event) error {
	log.Printf("Event ID: %s", e.ID())
	log.Printf("Event Type: %s", e.Type())

	var data storagedata.StorageObjectData
	if err := protojson.Unmarshal(e.Data(), &data); err != nil {
		return fmt.Errorf("protojson.Unmarshal: %w", err)
	}

	log.Printf("Bucket: %s", data.GetBucket())
	log.Printf("File: %s", data.GetName())
	log.Printf("Metageneration: %d", data.GetMetageneration())
	log.Printf("Created: %s", data.GetTimeCreated().AsTime())
	log.Printf("Updated: %s", data.GetUpdated().AsTime())
	return nil
}

Java

import com.google.cloud.functions.CloudEventsFunction;
import com.google.events.cloud.storage.v1.StorageObjectData;
import com.google.protobuf.InvalidProtocolBufferException;
import com.google.protobuf.util.JsonFormat;
import io.cloudevents.CloudEvent;
import java.nio.charset.StandardCharsets;
import java.util.logging.Logger;

public class HelloGcs implements CloudEventsFunction {
  private static final Logger logger = Logger.getLogger(HelloGcs.class.getName());

  @Override
  public void accept(CloudEvent event) throws InvalidProtocolBufferException {
    logger.info("Event: " + event.getId());
    logger.info("Event Type: " + event.getType());

    if (event.getData() == null) {
      logger.warning("No data found in cloud event payload!");
      return;
    }

    String cloudEventData = new String(event.getData().toBytes(), StandardCharsets.UTF_8);
    StorageObjectData.Builder builder = StorageObjectData.newBuilder();
    JsonFormat.parser().merge(cloudEventData, builder);
    StorageObjectData data = builder.build();

    logger.info("Bucket: " + data.getBucket());
    logger.info("File: " + data.getName());
    logger.info("Metageneration: " + data.getMetageneration());
    logger.info("Created: " + data.getTimeCreated());
    logger.info("Updated: " + data.getUpdated());
  }
}

C#

using CloudNative.CloudEvents;
using Google.Cloud.Functions.Framework;
using Google.Events.Protobuf.Cloud.Storage.V1;
using Microsoft.Extensions.Logging;
using System.Threading;
using System.Threading.Tasks;

namespace HelloGcs;

 /// <summary>
 /// Example Cloud Storage-triggered function.
 /// This function can process any event from Cloud Storage.
 /// </summary>
public class Function : ICloudEventFunction<StorageObjectData>
{
    private readonly ILogger _logger;

    public Function(ILogger<Function> logger) =>
        _logger = logger;

    public Task HandleAsync(CloudEvent cloudEvent, StorageObjectData data, CancellationToken cancellationToken)
    {
        _logger.LogInformation("Event: {event}", cloudEvent.Id);
        _logger.LogInformation("Event Type: {type}", cloudEvent.Type);
        _logger.LogInformation("Bucket: {bucket}", data.Bucket);
        _logger.LogInformation("File: {file}", data.Name);
        _logger.LogInformation("Metageneration: {metageneration}", data.Metageneration);
        _logger.LogInformation("Created: {created:s}", data.TimeCreated?.ToDateTimeOffset());
        _logger.LogInformation("Updated: {updated:s}", data.Updated?.ToDateTimeOffset());
        return Task.CompletedTask;
    }
}

Ruby

require "functions_framework"

FunctionsFramework.cloud_event "hello_gcs" do |event|
  # This function supports all Cloud Storage events.
  # The `event` parameter is a CloudEvents::Event::V1 object.
  # See https://cloudevents.github.io/sdk-ruby/latest/CloudEvents/Event/V1.html
  payload = event.data

  logger.info "Event: #{event.id}"
  logger.info "Event Type: #{event.type}"
  logger.info "Bucket: #{payload['bucket']}"
  logger.info "File: #{payload['name']}"
  logger.info "Metageneration: #{payload['metageneration']}"
  logger.info "Created: #{payload['timeCreated']}"
  logger.info "Updated: #{payload['updated']}"
end

PHP


use CloudEvents\V1\CloudEventInterface;
use Google\CloudFunctions\FunctionsFramework;

// Register the function with Functions Framework.
// This enables omitting the `FUNCTIONS_SIGNATURE_TYPE=cloudevent` environment
// variable when deploying. The `FUNCTION_TARGET` environment variable should
// match the first parameter.
FunctionsFramework::cloudEvent('helloGCS', 'helloGCS');

function helloGCS(CloudEventInterface $cloudevent)
{
    // This function supports all Cloud Storage event types.
    $log = fopen(getenv('LOGGER_OUTPUT') ?: 'php://stderr', 'wb');
    $data = $cloudevent->getData();
    fwrite($log, 'Event: ' . $cloudevent->getId() . PHP_EOL);
    fwrite($log, 'Event Type: ' . $cloudevent->getType() . PHP_EOL);
    fwrite($log, 'Bucket: ' . $data['bucket'] . PHP_EOL);
    fwrite($log, 'File: ' . $data['name'] . PHP_EOL);
    fwrite($log, 'Metageneration: ' . $data['metageneration'] . PHP_EOL);
    fwrite($log, 'Created: ' . $data['timeCreated'] . PHP_EOL);
    fwrite($log, 'Updated: ' . $data['updated'] . PHP_EOL);
}

如需部署该函数,请在示例代码所在的目录中运行以下命令:

Node.js

gcloud functions deploy nodejs-finalize-function \
--gen2 \
--runtime=nodejs20 \
--region=REGION \
--source=. \
--entry-point=helloGCS \
--trigger-event-filters="type=google.cloud.storage.object.v1.finalized" \
--trigger-event-filters="bucket=YOUR_BUCKET_NAME"

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

Python

gcloud functions deploy python-finalize-function \
--gen2 \
--runtime=python312 \
--region=REGION \
--source=. \
--entry-point=hello_gcs \
--trigger-event-filters="type=google.cloud.storage.object.v1.finalized" \
--trigger-event-filters="bucket=YOUR_BUCKET_NAME"

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

Go

gcloud functions deploy go-finalize-function \
--gen2 \
--runtime=go121 \
--region=REGION \
--source=. \
--entry-point=HelloStorage \
--trigger-event-filters="type=google.cloud.storage.object.v1.finalized" \
--trigger-event-filters="bucket=YOUR_BUCKET_NAME"

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

Java

gcloud functions deploy java-finalize-function \
--gen2 \
--runtime=java17 \
--region=REGION \
--source=. \
--entry-point=functions.HelloGcs \
--memory=512MB \
--trigger-event-filters="type=google.cloud.storage.object.v1.finalized" \
--trigger-event-filters="bucket=YOUR_BUCKET_NAME"

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

C#

gcloud functions deploy csharp-finalize-function \
--gen2 \
--runtime=dotnet6 \
--region=REGION \
--source=. \
--entry-point=HelloGcs.Function \
--trigger-event-filters="type=google.cloud.storage.object.v1.finalized" \
--trigger-event-filters="bucket=YOUR_BUCKET_NAME"

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

Ruby

gcloud functions deploy ruby-finalize-function \
--gen2 \
--runtime=ruby32 \
--region=REGION \
--source=. \
--entry-point=hello_gcs \
--trigger-event-filters="type=google.cloud.storage.object.v1.finalized" \
--trigger-event-filters="bucket=YOUR_BUCKET_NAME"

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

PHP

gcloud functions deploy php-finalize-function \
--gen2 \
--runtime=php82 \
--region=REGION \
--source=. \
--entry-point=helloGCS \
--trigger-event-filters="type=google.cloud.storage.object.v1.finalized" \
--trigger-event-filters="bucket=YOUR_BUCKET_NAME"

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

替换以下内容:

  • REGION:要在其中部署函数的 Google Cloud 区域的名称(例如 us-west1)。
  • YOUR_BUCKET_NAME:触发函数的 Cloud Storage 存储桶的名称。部署第 2 代函数时,请仅指定不含前导 gs:// 的存储桶名称;例如 --trigger-event-filters="bucket=my-bucket"

完成对象创建:触发函数

通过将文件上传到存储桶来测试函数:

echo "Hello World" > test-finalize.txt
gsutil cp test-finalize.txt gs://YOUR_BUCKET_NAME/test-finalize.txt

您应该会在日志中看到已接收到的 CloudEvent:

gcloud functions logs read YOUR_FUNCTION_NAME --region REGION --gen2 --limit=10

对象删除

对于未启用版本控制的存储分区,对象删除事件最实用。这些事件会在对象的旧版本被删除时触发。另外,当对象被覆盖时,这些事件也会触发。对象删除触发器也可以用于启用了版本控制的存储分区。当对象的某个版本被永久删除时,会触发此类触发器。

对象删除:部署函数

使用与“完成创建”示例相同的示例代码,以对象删除作为触发器事件来部署函数。在示例代码所在的目录中运行以下命令:

Node.js

gcloud functions deploy nodejs-delete-function \
--gen2 \
--runtime=nodejs20 \
--region=REGION \
--source=. \
--entry-point=helloGCS \
--trigger-event-filters="type=google.cloud.storage.object.v1.deleted" \
--trigger-event-filters="bucket=YOUR_BUCKET_NAME"

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

Python

gcloud functions deploy python-delete-function \
--gen2 \
--runtime=python312 \
--region=REGION \
--source=. \
--entry-point=hello_gcs \
--trigger-event-filters="type=google.cloud.storage.object.v1.deleted" \
--trigger-event-filters="bucket=YOUR_BUCKET_NAME"

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

Go

gcloud functions deploy go-delete-function \
--gen2 \
--runtime=go121 \
--region=REGION \
--source=. \
--entry-point=HelloStorage \
--trigger-event-filters="type=google.cloud.storage.object.v1.deleted" \
--trigger-event-filters="bucket=YOUR_BUCKET_NAME"

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

Java

gcloud functions deploy java-delete-function \
--gen2 \
--runtime=java17 \
--region=REGION \
--source=. \
--entry-point=functions.HelloGcs \
--memory=512MB \
--trigger-event-filters="type=google.cloud.storage.object.v1.deleted" \
--trigger-event-filters="bucket=YOUR_BUCKET_NAME"

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

C#

gcloud functions deploy csharp-delete-function \
--gen2 \
--runtime=dotnet6 \
--region=REGION \
--source=. \
--entry-point=HelloGcs.Function \
--trigger-event-filters="type=google.cloud.storage.object.v1.deleted" \
--trigger-event-filters="bucket=YOUR_BUCKET_NAME"

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

Ruby

gcloud functions deploy ruby-delete-function \
--gen2 \
--runtime=ruby32 \
--region=REGION \
--source=. \
--entry-point=hello_gcs \
--trigger-event-filters="type=google.cloud.storage.object.v1.deleted" \
--trigger-event-filters="bucket=YOUR_BUCKET_NAME"

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

PHP

gcloud functions deploy php-delete-function \
--gen2 \
--runtime=php82 \
--region=REGION \
--source=. \
--entry-point=helloGCS \
--trigger-event-filters="type=google.cloud.storage.object.v1.deleted" \
--trigger-event-filters="bucket=YOUR_BUCKET_NAME"

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

替换以下内容:

  • REGION:要在其中部署函数的 Google Cloud 区域的名称(例如 us-west1)。
  • YOUR_BUCKET_NAME:触发函数的 Cloud Storage 存储桶的名称。部署第 2 代函数时,请仅指定不含前导 gs:// 的存储桶名称;例如 --trigger-event-filters="bucket=my-bucket"

对象删除:触发函数

如需触发函数,请执行以下操作:

  1. 在示例代码所在的目录中创建一个空 test-delete.txt 文件。

  2. 确保您的存储分区未启用版本控制:

    gsutil versioning set off gs://YOUR_BUCKET_NAME
    
  3. 将该文件上传到 Cloud Storage:

    gsutil cp test-delete.txt gs://YOUR_BUCKET_NAME
    

    其中,YOUR_BUCKET_NAME 是您要向其中上传测试文件的 Cloud Storage 存储分区的名称。此时,函数应该尚未执行。

  4. 删除该文件以触发函数:

    gsutil rm gs://YOUR_BUCKET_NAME/test-delete.txt
    
  5. 您应该会在日志中看到已接收到的 CloudEvent:

    gcloud functions logs read YOUR_FUNCTION_NAME --region REGION --gen2 --limit=10

请注意,函数可能需要一些时间才能执行完毕。

对象归档

对象归档事件只能用于启用了版本控制的存储分区。这些事件会在对象的早期版本被归档时触发。具体而言,这意味着当对象被覆盖或删除时,归档事件会被触发。

对象归档:部署函数

使用与“完成创建”示例相同的示例代码,以对象归档作为触发器事件来部署函数。在示例代码所在的目录中运行以下命令:

Node.js

gcloud functions deploy nodejs-archive-function \
--gen2 \
--runtime=nodejs20 \
--region=REGION \
--source=. \
--entry-point=helloGCS \
--trigger-event-filters="type=google.cloud.storage.object.v1.archived" \
--trigger-event-filters="bucket=YOUR_BUCKET_NAME"

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

Python

gcloud functions deploy python-archive-function \
--gen2 \
--runtime=python312 \
--region=REGION \
--source=. \
--entry-point=hello_gcs \
--trigger-event-filters="type=google.cloud.storage.object.v1.archived" \
--trigger-event-filters="bucket=YOUR_BUCKET_NAME"

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

Go

gcloud functions deploy go-archive-function \
--gen2 \
--runtime=go121 \
--region=REGION \
--source=. \
--entry-point=HelloStorage \
--trigger-event-filters="type=google.cloud.storage.object.v1.archived" \
--trigger-event-filters="bucket=YOUR_BUCKET_NAME"

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

Java

gcloud functions deploy java-archive-function \
--gen2 \
--runtime=java17 \
--region=REGION \
--source=. \
--entry-point=functions.HelloGcs \
--memory=512MB \
--trigger-event-filters="type=google.cloud.storage.object.v1.archived" \
--trigger-event-filters="bucket=YOUR_BUCKET_NAME"

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

C#

gcloud functions deploy csharp-archive-function \
--gen2 \
--runtime=dotnet6 \
--region=REGION \
--source=. \
--entry-point=HelloGcs.Function \
--trigger-event-filters="type=google.cloud.storage.object.v1.archived" \
--trigger-event-filters="bucket=YOUR_BUCKET_NAME"

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

Ruby

gcloud functions deploy ruby-archive-function \
--gen2 \
--runtime=ruby32 \
--region=REGION \
--source=. \
--entry-point=hello_gcs \
--trigger-event-filters="type=google.cloud.storage.object.v1.archived" \
--trigger-event-filters="bucket=YOUR_BUCKET_NAME"

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

PHP

gcloud functions deploy php-archive-function \
--gen2 \
--runtime=php82 \
--region=REGION \
--source=. \
--entry-point=helloGCS \
--trigger-event-filters="type=google.cloud.storage.object.v1.archived" \
--trigger-event-filters="bucket=YOUR_BUCKET_NAME"

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

替换以下内容:

  • REGION:要在其中部署函数的 Google Cloud 区域的名称(例如 us-west1)。
  • YOUR_BUCKET_NAME:触发函数的 Cloud Storage 存储桶的名称。部署第 2 代函数时,请仅指定不含前导 gs:// 的存储桶名称;例如 --trigger-event-filters="bucket=my-bucket"

对象归档:触发函数

如需触发函数,请执行以下操作:

  1. 在示例代码所在的目录中创建一个空 test-archive.txt 文件。

  2. 确保您的存储分区已启用版本控制:

    gsutil versioning set on gs://YOUR_BUCKET_NAME
    
  3. 将该文件上传到 Cloud Storage:

    gsutil cp test-archive.txt gs://YOUR_BUCKET_NAME
    

    其中,YOUR_BUCKET_NAME 是您要向其中上传测试文件的 Cloud Storage 存储分区的名称。此时,函数应该尚未执行。

  4. 归档该文件以触发函数:

    gsutil rm gs://YOUR_BUCKET_NAME/test-archive.txt
    
  5. 您应该会在日志中看到已接收到的 CloudEvent:

    gcloud functions logs read YOUR_FUNCTION_NAME --region REGION --gen2 --limit=10

对象元数据更新

当现有对象的元数据更新时,元数据更新事件会被触发。

对象元数据更新:部署函数

使用与“完成创建”示例相同的示例代码,以元数据更新作为触发器事件来部署函数。在示例代码所在的目录中运行以下命令:

Node.js

gcloud functions deploy nodejs-metadata-function \
--gen2 \
--runtime=nodejs20 \
--region=REGION \
--source=. \
--entry-point=helloGCS \
--trigger-event-filters="type=google.cloud.storage.object.v1.metadataUpdated" \
--trigger-event-filters="bucket=YOUR_BUCKET_NAME"

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

Python

gcloud functions deploy python-metadata-function \
--gen2 \
--runtime=python312 \
--region=REGION \
--source=. \
--entry-point=hello_gcs \
--trigger-event-filters="type=google.cloud.storage.object.v1.metadataUpdated" \
--trigger-event-filters="bucket=YOUR_BUCKET_NAME"

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

Go

gcloud functions deploy go-metadata-function \
--gen2 \
--runtime=go121 \
--region=REGION \
--source=. \
--entry-point=HelloStorage \
--trigger-event-filters="type=google.cloud.storage.object.v1.metadataUpdated" \
--trigger-event-filters="bucket=YOUR_BUCKET_NAME"

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

Java

gcloud functions deploy java-metadata-function \
--gen2 \
--runtime=java17 \
--region=REGION \
--source=. \
--entry-point=functions.HelloGcs \
--memory=512MB \
--trigger-event-filters="type=google.cloud.storage.object.v1.metadataUpdated" \
--trigger-event-filters="bucket=YOUR_BUCKET_NAME"

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

C#

gcloud functions deploy csharp-metadata-function \
--gen2 \
--runtime=dotnet6 \
--region=REGION \
--source=. \
--entry-point=HelloGcs.Function \
--trigger-event-filters="type=google.cloud.storage.object.v1.metadataUpdated" \
--trigger-event-filters="bucket=YOUR_BUCKET_NAME"

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

Ruby

gcloud functions deploy ruby-metadata-function \
--gen2 \
--runtime=ruby32 \
--region=REGION \
--source=. \
--entry-point=hello_gcs \
--trigger-event-filters="type=google.cloud.storage.object.v1.metadataUpdated" \
--trigger-event-filters="bucket=YOUR_BUCKET_NAME"

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

PHP

gcloud functions deploy php-metadata-function \
--gen2 \
--runtime=php82 \
--region=REGION \
--source=. \
--entry-point=helloGCS \
--trigger-event-filters="type=google.cloud.storage.object.v1.metadataUpdated" \
--trigger-event-filters="bucket=YOUR_BUCKET_NAME"

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

替换以下内容:

  • REGION:要在其中部署函数的 Google Cloud 区域的名称(例如 us-west1)。
  • YOUR_BUCKET_NAME:触发函数的 Cloud Storage 存储桶的名称。部署第 2 代函数时,请仅指定不含前导 gs:// 的存储桶名称;例如 --trigger-event-filters="bucket=my-bucket"

对象元数据更新:触发函数

如需触发函数,请执行以下操作:

  1. 在示例代码所在的目录中创建一个空 test-metadata.txt 文件。

  2. 确保您的存储分区未启用版本控制:

    gsutil versioning set off gs://YOUR_BUCKET_NAME
    
  3. 将该文件上传到 Cloud Storage:

    gsutil cp test-metadata.txt gs://YOUR_BUCKET_NAME
    

    其中,YOUR_BUCKET_NAME 是您要向其中上传测试文件的 Cloud Storage 存储分区的名称。此时,函数应该尚未执行。

  4. 更新该文件的元数据:

    gsutil -m setmeta -h "Content-Type:text/plain" gs://YOUR_BUCKET_NAME/test-metadata.txt
    
  5. 您应该会在日志中看到已接收到的 CloudEvent:

    gcloud functions logs read YOUR_FUNCTION_NAME --region REGION --gen2 --limit=10

清理

为避免因本教程中使用的资源导致您的 Google Cloud 账号产生费用,请删除包含这些资源的项目,或者保留项目但删除各个资源。

删除项目

为了避免产生费用,最简单的方法是删除您为本教程创建的项目。

要删除项目,请执行以下操作:

  1. 在 Google Cloud 控制台中,进入管理资源页面。

    转到“管理资源”

  2. 在项目列表中,选择要删除的项目,然后点击删除
  3. 在对话框中输入项目 ID,然后点击关闭以删除项目。

删除 Cloud Functions 函数

删除 Cloud Functions 函数不会移除存储在 Cloud Storage 中的任何资源。

如需删除您在本教程中创建的 Cloud Functions 函数,请运行以下命令:

gcloud functions delete YOUR_FUNCTION_NAME --gen2 --region REGION

您也可以通过 Google Cloud 控制台删除 Cloud Functions 函数。

后续步骤