Cloud Storage 教程(第 1 代)


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

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

目标

费用

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

  • Cloud Functions
  • Cloud Storage

您可使用价格计算器根据您的预计使用情况来估算费用。 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, Cloud Storage, and Eventarc 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, Cloud Storage, and Eventarc API。

    启用 API

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

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

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

准备应用

  1. 创建一个 Cloud Storage 存储分区以向其中上传测试文件,其中,YOUR_TRIGGER_BUCKET_NAME 是全局唯一的存储分区名称:

    gsutil mb gs://YOUR_TRIGGER_BUCKET_NAME
    
  2. 将示例应用代码库克隆到本地机器:

    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 文件并将其解压缩。

  3. 切换到包含 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/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

/**
 * Generic background Cloud Function to be triggered by Cloud Storage.
 * This sample works for all Cloud Storage CRUD operations.
 *
 * @param {object} file The Cloud Storage file metadata.
 * @param {object} context The event metadata.
 */
exports.helloGCS = (file, context) => {
  console.log(`  Event: ${context.eventId}`);
  console.log(`  Event Type: ${context.eventType}`);
  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

def hello_gcs(event, context):
    """Background Cloud Function to be triggered by Cloud Storage.
       This generic function logs relevant data when a file is changed,
       and works for all Cloud Storage CRUD operations.
    Args:
        event (dict):  The dictionary with data specific to this type of event.
                       The `data` field contains a description of the event in
                       the Cloud Storage `object` format described here:
                       https://cloud.google.com/storage/docs/json_api/v1/objects#resource
        context (google.cloud.functions.Context): Metadata of triggering event.
    Returns:
        None; the output is written to Cloud Logging
    """

    print(f"Event ID: {context.event_id}")
    print(f"Event type: {context.event_type}")
    print("Bucket: {}".format(event["bucket"]))
    print("File: {}".format(event["name"]))
    print("Metageneration: {}".format(event["metageneration"]))
    print("Created: {}".format(event["timeCreated"]))
    print("Updated: {}".format(event["updated"]))

Go


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

import (
	"context"
	"fmt"
	"log"
	"time"

	"cloud.google.com/go/functions/metadata"
)

// GCSEvent is the payload of a GCS event.
type GCSEvent struct {
	Kind                    string                 `json:"kind"`
	ID                      string                 `json:"id"`
	SelfLink                string                 `json:"selfLink"`
	Name                    string                 `json:"name"`
	Bucket                  string                 `json:"bucket"`
	Generation              string                 `json:"generation"`
	Metageneration          string                 `json:"metageneration"`
	ContentType             string                 `json:"contentType"`
	TimeCreated             time.Time              `json:"timeCreated"`
	Updated                 time.Time              `json:"updated"`
	TemporaryHold           bool                   `json:"temporaryHold"`
	EventBasedHold          bool                   `json:"eventBasedHold"`
	RetentionExpirationTime time.Time              `json:"retentionExpirationTime"`
	StorageClass            string                 `json:"storageClass"`
	TimeStorageClassUpdated time.Time              `json:"timeStorageClassUpdated"`
	Size                    string                 `json:"size"`
	MD5Hash                 string                 `json:"md5Hash"`
	MediaLink               string                 `json:"mediaLink"`
	ContentEncoding         string                 `json:"contentEncoding"`
	ContentDisposition      string                 `json:"contentDisposition"`
	CacheControl            string                 `json:"cacheControl"`
	Metadata                map[string]interface{} `json:"metadata"`
	CRC32C                  string                 `json:"crc32c"`
	ComponentCount          int                    `json:"componentCount"`
	Etag                    string                 `json:"etag"`
	CustomerEncryption      struct {
		EncryptionAlgorithm string `json:"encryptionAlgorithm"`
		KeySha256           string `json:"keySha256"`
	}
	KMSKeyName    string `json:"kmsKeyName"`
	ResourceState string `json:"resourceState"`
}

// HelloGCS consumes a(ny) GCS event.
func HelloGCS(ctx context.Context, e GCSEvent) error {
	meta, err := metadata.FromContext(ctx)
	if err != nil {
		return fmt.Errorf("metadata.FromContext: %w", err)
	}
	log.Printf("Event ID: %v\n", meta.EventID)
	log.Printf("Event type: %v\n", meta.EventType)
	log.Printf("Bucket: %v\n", e.Bucket)
	log.Printf("File: %v\n", e.Name)
	log.Printf("Metageneration: %v\n", e.Metageneration)
	log.Printf("Created: %v\n", e.TimeCreated)
	log.Printf("Updated: %v\n", e.Updated)
	return nil
}

Java

import com.google.cloud.functions.BackgroundFunction;
import com.google.cloud.functions.Context;
import functions.eventpojos.GcsEvent;
import java.util.logging.Logger;

/**
 * Example Cloud Storage-triggered function.
 * This function can process any event from Cloud Storage.
 */
public class HelloGcs implements BackgroundFunction<GcsEvent> {
  private static final Logger logger = Logger.getLogger(HelloGcs.class.getName());

  @Override
  public void accept(GcsEvent event, Context context) {
    logger.info("Event: " + context.eventId());
    logger.info("Event Type: " + context.eventType());
    logger.info("Bucket: " + event.getBucket());
    logger.info("File: " + event.getName());
    logger.info("Metageneration: " + event.getMetageneration());
    logger.info("Created: " + event.getTimeCreated());
    logger.info("Updated: " + event.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 helloGCS \
--runtime nodejs20 \
--trigger-resource YOUR_TRIGGER_BUCKET_NAME \
--trigger-event google.storage.object.finalize

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

Python

gcloud functions deploy hello_gcs \
--runtime python312 \
--trigger-resource YOUR_TRIGGER_BUCKET_NAME \
--trigger-event google.storage.object.finalize

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

Go

gcloud functions deploy HelloGCS \
--runtime go121 \
--trigger-resource YOUR_TRIGGER_BUCKET_NAME \
--trigger-event google.storage.object.finalize

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

Java

gcloud functions deploy java-gcs-function \
--entry-point functions.HelloGcs \
--runtime java17 \
--memory 512MB \
--trigger-resource YOUR_TRIGGER_BUCKET_NAME \
--trigger-event google.storage.object.finalize

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

C#

gcloud functions deploy csharp-gcs-function \
--entry-point HelloGcs.Function \
--runtime dotnet6 \
--trigger-resource YOUR_TRIGGER_BUCKET_NAME \
--trigger-event google.storage.object.finalize

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

Ruby

gcloud functions deploy hello_gcs --runtime ruby32 \
--trigger-resource YOUR_TRIGGER_BUCKET_NAME \
--trigger-event google.storage.object.finalize

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

PHP

 gcloud functions deploy helloGCS --runtime php82 \
--trigger-resource YOUR_TRIGGER_BUCKET_NAME \
--trigger-event google.storage.object.finalize

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

其中,YOUR_TRIGGER_BUCKET_NAME 是触发函数的 Cloud Storage 存储分区的名称。

完成对象创建:触发函数

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

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

  2. 将该文件上传到 Cloud Storage 以触发函数:

    gsutil cp gcf-test.txt gs://YOUR_TRIGGER_BUCKET_NAME
    

    其中,YOUR_TRIGGER_BUCKET_NAME 是您要向其中上传测试文件的 Cloud Storage 存储分区的名称。

  3. 检查日志以确保执行已完成:

    gcloud functions logs read --limit 50
    

对象删除

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

对象删除:部署函数

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

Node.js

gcloud functions deploy helloGCS \
--runtime nodejs20 \
--trigger-resource YOUR_TRIGGER_BUCKET_NAME \
--trigger-event google.storage.object.delete

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

Python

gcloud functions deploy hello_gcs \
--runtime python312 \
--trigger-resource YOUR_TRIGGER_BUCKET_NAME \
--trigger-event google.storage.object.delete

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

Go

gcloud functions deploy HelloGCS \
--runtime go121 \
--trigger-resource YOUR_TRIGGER_BUCKET_NAME \
--trigger-event google.storage.object.delete

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

Java

gcloud functions deploy java-gcs-function \
--entry-point functions.HelloGcs \
--runtime java17 \
--memory 512MB \
--trigger-resource YOUR_TRIGGER_BUCKET_NAME \
--trigger-event google.storage.object.delete

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

C#

gcloud functions deploy csharp-gcs-function \
--entry-point HelloGcs.Function \
--runtime dotnet6 \
--trigger-resource YOUR_TRIGGER_BUCKET_NAME \
--trigger-event google.storage.object.delete

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

Ruby

gcloud functions deploy hello_gcs --runtime ruby32 \
--trigger-resource YOUR_TRIGGER_BUCKET_NAME \
--trigger-event google.storage.object.delete

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

PHP

 gcloud functions deploy helloGCS --runtime php82 \
--trigger-resource YOUR_TRIGGER_BUCKET_NAME \
--trigger-event google.storage.object.delete

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

其中,YOUR_TRIGGER_BUCKET_NAME 是触发函数的 Cloud Storage 存储分区的名称。

对象删除:触发函数

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

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

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

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

    gsutil cp gcf-test.txt gs://YOUR_TRIGGER_BUCKET_NAME
    

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

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

    gsutil rm gs://YOUR_TRIGGER_BUCKET_NAME/gcf-test.txt
    
  5. 检查日志以确保执行已完成:

    gcloud functions logs read --limit 50
    

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

对象归档

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

对象归档:部署函数

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

Node.js

gcloud functions deploy helloGCS \
--runtime nodejs20 \
--trigger-resource YOUR_TRIGGER_BUCKET_NAME \
--trigger-event google.storage.object.archive

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

Python

gcloud functions deploy hello_gcs \
--runtime python312 \
--trigger-resource YOUR_TRIGGER_BUCKET_NAME \
--trigger-event google.storage.object.archive

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

Go

gcloud functions deploy HelloGCS \
--runtime go121 \
--trigger-resource YOUR_TRIGGER_BUCKET_NAME \
--trigger-event google.storage.object.archive

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

Java

gcloud functions deploy java-gcs-function \
--entry-point functions.HelloGcs \
--runtime java17 \
--memory 512MB \
--trigger-resource YOUR_TRIGGER_BUCKET_NAME \
--trigger-event google.storage.object.archive

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

C#

gcloud functions deploy csharp-gcs-function \
--entry-point HelloGcs.Function \
--runtime dotnet6 \
--trigger-resource YOUR_TRIGGER_BUCKET_NAME \
--trigger-event google.storage.object.archive

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

Ruby

gcloud functions deploy hello_gcs --runtime ruby32 \
--trigger-resource YOUR_TRIGGER_BUCKET_NAME \
--trigger-event google.storage.object.archive

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

PHP

 gcloud functions deploy helloGCS --runtime php82 \
--trigger-resource YOUR_TRIGGER_BUCKET_NAME \
--trigger-event google.storage.object.archive

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

其中,YOUR_TRIGGER_BUCKET_NAME 是触发函数的 Cloud Storage 存储分区的名称。

对象归档:触发函数

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

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

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

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

    gsutil cp gcf-test.txt gs://YOUR_TRIGGER_BUCKET_NAME
    

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

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

    gsutil rm gs://YOUR_TRIGGER_BUCKET_NAME/gcf-test.txt
    
  5. 查看日志以确保执行已完成:

    gcloud functions logs read --limit 50
    

对象元数据更新

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

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

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

Node.js

gcloud functions deploy helloGCS \
--runtime nodejs20 \
--trigger-resource YOUR_TRIGGER_BUCKET_NAME \
--trigger-event google.storage.object.metadataUpdate

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

Python

gcloud functions deploy hello_gcs \
--runtime python312 \
--trigger-resource YOUR_TRIGGER_BUCKET_NAME \
--trigger-event google.storage.object.metadataUpdate

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

Go

gcloud functions deploy HelloGCS \
--runtime go121 \
--trigger-resource YOUR_TRIGGER_BUCKET_NAME \
--trigger-event google.storage.object.metadataUpdate

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

Java

gcloud functions deploy java-gcs-function \
--entry-point functions.HelloGcs \
--runtime java17 \
--memory 512MB \
--trigger-resource YOUR_TRIGGER_BUCKET_NAME \
--trigger-event google.storage.object.metadataUpdate

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

C#

gcloud functions deploy csharp-gcs-function \
--entry-point HelloGcs.Function \
--runtime dotnet6 \
--trigger-resource YOUR_TRIGGER_BUCKET_NAME \
--trigger-event google.storage.object.metadataUpdate

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

Ruby

gcloud functions deploy hello_gcs --runtime ruby32 \
--trigger-resource YOUR_TRIGGER_BUCKET_NAME \
--trigger-event google.storage.object.metadataUpdate

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

PHP

 gcloud functions deploy helloGCS --runtime php82 \
--trigger-resource YOUR_TRIGGER_BUCKET_NAME \
--trigger-event google.storage.object.metadataUpdate

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

其中,YOUR_TRIGGER_BUCKET_NAME 是触发函数的 Cloud Storage 存储分区的名称。

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

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

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

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

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

    gsutil cp gcf-test.txt gs://YOUR_TRIGGER_BUCKET_NAME
    

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

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

    gsutil -m setmeta -h "Content-Type:text/plain" gs://YOUR_TRIGGER_BUCKET_NAME/gcf-test.txt
    
  5. 查看日志以确保执行已完成:

    gcloud functions logs read --limit 50
    

清理

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

删除项目

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

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

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

    转到“管理资源”

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

删除 Cloud Functions 函数

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

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

Node.js

gcloud functions delete helloGCS 

Python

gcloud functions delete hello_gcs 

Go

gcloud functions delete HelloGCS 

Java

gcloud functions delete java-gcs-function 

C#

gcloud functions delete csharp-gcs-function 

Ruby

gcloud functions delete hello_gcs 

PHP

gcloud functions delete helloGCS 

您也可以通过 Google Cloud Console 删除 Cloud Functions 函数。

后续步骤