执行此操作的方法是为新对象创建 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