执行此操作的方法是为新对象创建 Cloud Pub/Sub 主题,并配置您的 GCS 存储桶以在创建新对象时将消息发布到该主题。
首先,让我们创建一个存储桶 PHOTOBUCKET:
$ gsutil mb gs://PHOTOBUCKET
现在,请确保您已activated the Cloud Pub/Sub API。
接下来,让我们创建一个 Cloud Pub/Sub 主题并使用 gsutil 将其连接到我们的 GCS 存储桶:
$ gsutil notification create \
-t uploadedphotos -f json \
-e OBJECT_FINALIZE gs://PHOTOBUCKET
-t 指定 Pub/Sub 主题。如果该主题尚不存在,gsutil 将为您创建它。
-e 指定您只对 OBJECT_FINALIZE 消息(正在创建的对象)感兴趣。否则,您将收到主题中的各种消息。
-f 指定您希望消息的有效负载是 JSON API 的对象元数据。
请注意,这需要最新版本的 gsutil,因此请务必更新到最新版本的 gcloud,如果您使用独立的 gsutil,请运行 gsutil update。
现在我们已配置并发送通知,但我们希望看到它们。让我们创建一个 Pub/Sub 订阅:
$ gcloud beta pubsub 订阅创建 processphotos --topic=uploadedphotos
现在我们只需要阅读这些消息。 Here's a Python example 这样做。以下是相关位:
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/pubsub-notifications