Open NeroCube opened 1 year ago
# 引入所需的模組 import base64 import json from google.cloud import pubsub_v1 # 設定目標project和topic的ID target_project_id = "your-target-project-id" target_topic_id = "your-target-topic-id" # 建立一個pubsub發佈者客戶端 publisher = pubsub_v1.PublisherClient() # 構建目標topic的名稱 target_topic_name = f"projects/{target_project_id}/topics/{target_topic_id}" # 定義一個cloud function,接收來自pubsub訂閱的事件和上下文 def forward_metrics(event, context): # 從事件中解碼和解析metrics數據 data = base64.b64decode(event["data"]).decode("utf-8") metrics = json.loads(data) print(f"Received metrics: {metrics}") # 將metrics數據轉換為字節串,準備發佈到目標topic data = json.dumps(metrics).encode("utf-8") # 發佈metrics數據到目標topic,並打印結果 future = publisher.publish(target_topic_name, data) message_id = future.result() print(f"Published metrics to {target_topic_name} with message ID: {message_id}")
您可以參考以下的資源來了解更多關於python cloud function和pubsub的用法:
Source: Conversation with Bing, 2023/8/3 (1) Pub/Sub publish message | Cloud Functions Documentation | Google Cloud. https://cloud.google.com/functions/docs/samples/functions-pubsub-publish. (2) Cloud Pub/Sub Tutorial (2nd gen) | Cloud Functions Documentation | Google Cloud. https://cloud.google.com/functions/docs/tutorials/pubsub. (3) python - Consume PubSub in Google cloud function - Stack Overflow. https://stackoverflow.com/questions/63025107/consume-pubsub-in-google-cloud-function.
您可以參考以下的資源來了解更多關於python cloud function和pubsub的用法:
Source: Conversation with Bing, 2023/8/3 (1) Pub/Sub publish message | Cloud Functions Documentation | Google Cloud. https://cloud.google.com/functions/docs/samples/functions-pubsub-publish. (2) Cloud Pub/Sub Tutorial (2nd gen) | Cloud Functions Documentation | Google Cloud. https://cloud.google.com/functions/docs/tutorials/pubsub. (3) python - Consume PubSub in Google cloud function - Stack Overflow. https://stackoverflow.com/questions/63025107/consume-pubsub-in-google-cloud-function.