配置适用于 Cloud Storage 的 Pub/Sub 通知

概览

本页面介绍了如何配置存储桶,以将有关对象更改的通知发送到 Pub/Sub 主题。如需了解如何订阅可接收通知的 Pub/Sub 主题,请参阅选择订阅类型

准备工作

要使用此功能,请先按照以下说明完成操作。

启用 Pub/Sub API

为将接收通知的项目启用 Pub/Sub API。

启用 API

获取所需角色

如需获得配置和查看存储桶的 Pub/Sub 通知所需的权限,请让您的管理员为您授予以下角色。这些预定义角色包含配置和查看 Pub/Sub 通知所需的权限。

  • 要为其配置 Pub/Sub 通知的存储桶的 Storage Admin (roles/storage.admin) 角色

  • 要在其中接收 Pub/Sub 通知的项目的 Pub/Sub Admin (roles/pubsub.admin) 角色

您可以使用其他预定义角色自定义角色来获取这些权限。

如需了解如何授予存储桶的角色,请参阅为存储桶设置和管理 IAM 政策。如需了解如何授予项目的角色以及为主题和订阅设置访问权限控制,请参阅控制访问权限

确保您已具有现有的 Pub/Sub 主题

如果尚未创建,请创建 Pub/Sub 主题以向其发送通知。如果您计划使用 Google Cloud CLI 或 Terraform 执行本页面上的说明,则无需执行此步骤。

向项目的服务代理授予所需角色

如果您计划使用 Google Cloud CLI 或 Terraform 来执行本页面上的说明,则无需执行以下步骤。

  1. 获取与包含 Cloud Storage 存储桶的项目关联的服务代理的电子邮件地址

  2. 为服务代理授予相关 Pub/Sub 主题的 Pub/Sub Publisher (roles/pubsub.publisher) 角色。如需了解如何授予主题的角色,请参阅控制访问权限

应用通知配置

以下步骤将向您的存储桶添加通知配置,用于为所有支持的事件发送通知。

控制台

您无法使用Google Cloud 控制台来管理 Pub/Sub 通知。请改用 gcloud CLI 或某一可用的客户端库。

命令行

使用 gcloud storage buckets notifications create 命令

gcloud storage buckets notifications create gs://BUCKET_NAME --topic=TOPIC_NAME

其中:

  • BUCKET_NAME 是相关存储桶的名称,例如 my-bucket

  • TOPIC_NAME 是要向其发送通知的 Pub/Sub 主题。如果您指定项目中不存在的主题,该命令会为您创建该主题。

如需为一部分事件发送通知,请添加 --event-types 标志

客户端库

C++

如需了解详情,请参阅 Cloud Storage C++ API 参考文档

如需向 Cloud Storage 进行身份验证,请设置应用默认凭证。如需了解详情,请参阅为客户端库设置身份验证

namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
   std::string const& topic_name) {
  StatusOr<gcs::NotificationMetadata> notification =
      client.CreateNotification(bucket_name, topic_name,
                                gcs::NotificationMetadata());
  if (!notification) throw std::move(notification).status();

  std::cout << "Successfully created notification " << notification->id()
            << " for bucket " << bucket_name << "\n";
  std::cout << "Full details for the notification:\n"
            << *notification << "\n";
}

C#

如需了解详情,请参阅 Cloud Storage C# API 参考文档

如需向 Cloud Storage 进行身份验证,请设置应用默认凭证。如需了解详情,请参阅为客户端库设置身份验证


using Google.Apis.Storage.v1.Data;
using Google.Cloud.Storage.V1;
using System;

public class CreatePubSubNotificationSample
{
    public Notification CreatePubSubNotification(
        string bucketName = "your-unique-bucket-name",
        string topic = "my-topic")
    {
        StorageClient storage = StorageClient.Create();
        Notification notification = new Notification
        {
            Topic = topic,
            PayloadFormat = "JSON_API_V1"
        };

        Notification createdNotification = storage.CreateNotification(bucketName, notification);
        Console.WriteLine("Notification subscription created with ID: " + createdNotification.Id + " for bucket name " + bucketName);
        return createdNotification;
    }
}

Go

如需了解详情,请参阅 Cloud Storage Go API 参考文档

如需向 Cloud Storage 进行身份验证,请设置应用默认凭证。如需了解详情,请参阅为客户端库设置身份验证

import (
	"context"
	"fmt"
	"io"

	"cloud.google.com/go/storage"
)

// createBucketNotification creates a notification configuration for a bucket.
func createBucketNotification(w io.Writer, projectID, bucketName, topic string) error {
	// projectID := "my-project-id"
	// bucketName := "bucket-name"
	// topic := "topic-name"

	ctx := context.Background()
	client, err := storage.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("storage.NewClient: %w", err)
	}
	defer client.Close()

	notification := storage.Notification{
		TopicID:        topic,
		TopicProjectID: projectID,
		PayloadFormat:  storage.JSONPayload,
	}

	createdNotification, err := client.Bucket(bucketName).AddNotification(ctx, &notification)
	if err != nil {
		return fmt.Errorf("Bucket.AddNotification: %w", err)
	}
	fmt.Fprintf(w, "Successfully created notification with ID %s for bucket %s.\n", createdNotification.ID, bucketName)
	return nil
}

Java

如需了解详情,请参阅 Cloud Storage Java API 参考文档

如需向 Cloud Storage 进行身份验证,请设置应用默认凭证。如需了解详情,请参阅为客户端库设置身份验证

import com.google.cloud.storage.Notification;
import com.google.cloud.storage.NotificationInfo;
import com.google.cloud.storage.NotificationInfo.EventType;
import com.google.cloud.storage.NotificationInfo.PayloadFormat;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
import java.util.Map;

public class CreateBucketPubSubNotification {

  public static void createBucketPubSubNotification(
      String bucketName,
      String topicName,
      Map<String, String> customAttributes,
      EventType[] eventTypes,
      String objectNamePrefix,
      PayloadFormat payloadFormat) {
    // The ID to give your GCS bucket
    // String bucketName = "your-unique-bucket-name";

    // The name of the topic you would like to create a notification for
    // String topicName = "projects/{your-project}/topics/{your-topic}";

    // Any custom attributes
    // Map<String, String> customAttributes = Map.of("label", "value");

    // The object name prefix for which this notification configuration applies
    // String objectNamePrefix = "blob-";

    // Desired content of the Payload
    // PayloadFormat payloadFormat = PayloadFormat.JSON_API_V1.JSON_API_V1;

    Storage storage = StorageOptions.newBuilder().build().getService();
    NotificationInfo