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

Bra*_*ugh 7 google-cloud-storage google-cloud-platform google-cloud-pubsub

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

Bra*_*ugh 14

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

首先,让我们创建一个水桶PHOTOBUCKET:

$ gsutil mb gs://PHOTOBUCKET
Run Code Online (Sandbox Code Playgroud)

现在,请确保您已激活Cloud Pub/Sub API.

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

$ gsutil notification create \
    -t uploadedphotos -f json \
    -e OBJECT_FINALIZE gs://PHOTOBUCKET
Run Code Online (Sandbox Code Playgroud)

-t指定的发布/订阅主题.如果该主题尚不存在,gsutil将为您创建.

-e说你只是在OBJECT_FINALIZE消息感兴趣的指定(创建对象).否则,您将在主题中获得各种消息.

-f你想要的信息的有效载荷指定要用于JSON API的对象元数据.

请注意,这需要最新版本的gsutil,因此请确保更新到最新版本gcloud,或者在gsutil update使用独立gsutil时运行.

现在我们已经配置了通知和抽水,但我们希望看到它们.让我们创建一个Pub/Sub订阅:

$ gcloud beta pubsub subscriptions创建processphotos --topic = uploadedphotos

现在我们只需要阅读这些消息.这是一个Python的例子.以下是相关位:

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
Run Code Online (Sandbox Code Playgroud)

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

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