当对象上传到我的 GCS 存储桶时,如何收到通知?

2024-01-15

我有一个应用程序可以定期将照片上传到 GCS 存储桶。当这些照片上传后,我需要添加缩略图并进行一些分析。如何为存储桶设置通知?


执行此操作的方法是为新对象创建 Cloud Pub/Sub 主题,并配置 GCS 存储桶以在创建新对象时向该主题发布消息。

首先,我们创建一个存储桶 PHOTOBUCKET:

$ gsutil mb gs://PHOTOBUCKET

现在,请确保您已经.

接下来,让我们创建一个 Cloud Pub/Sub 主题并将其连接到我们的 GCS 存储桶:gsutil:

$ gsutil notification create \
    -t uploadedphotos -f json \
    -e OBJECT_FINALIZE gs://PHOTOBUCKET

The -t指定 Pub/Sub 主题。如果该主题尚不存在,gsutil将为您创建它。

The -e指定您只对 OBJECT_FINALIZE 消息(正在创建的对象)感兴趣。否则,您将收到主题中的各种消息。

The -f指定您希望消息的负载成为 JSON API 的对象元数据。

请注意,这需要最新版本的 gsutil,因此请务必更新到最新版本gcloud,或运行gsutil update如果您使用独立的 gsutil。

现在我们已经配置并发送了通知,但我们希望看到它们。让我们创建一个 Pub/Sub 订阅:

$ gcloud beta pubsub 订阅创建 processphotos --topic=uploadedphotos

现在我们只需要阅读这些消息。这是一个 Python 示例 https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/storage/cloud-client/notification_polling.py就是这样做的。以下是相关内容:

def poll_notifications(subscription_id):
    client = pubsub.Client()
    subscription = pubsub.subscription.Subscription(
        subscription_id, client=client)
    while True:
        pulled = subscription.pull(max_messages=100)
        for ack_id, message in pulled:
            print('Received message {0}:\n{1}'.format(
                message.message_id, summarize(message)))
            subscription.acknowledge([ack_id])

def summarize(message):
    # [START parse_message]
    data = message.data
    attributes = message.attributes

    event_type = attributes['eventType']
    bucket_id = attributes['bucketId']
    object_id = attributes['objectId']
    return "A user uploaded %s, we should do something here." % object_id

以下是有关该系统如何工作的更多阅读内容:

https://cloud.google.com/storage/docs/reporting-changes https://cloud.google.com/storage/docs/reporting-changes https://cloud.google.com/storage/docs/pubsub-notifications https://cloud.google.com/storage/docs/pubsub-notifications

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

当对象上传到我的 GCS 存储桶时,如何收到通知? 的相关文章

随机推荐