适用于 Pub/Sub 的连接器

定义用于在工作流内访问 Pub/Sub 的内置函数的 Workflows 连接器。

深入探索

如需查看包含此代码示例的详细文档,请参阅以下内容:

代码示例

YAML

# This workflow demonstrates how to use the Cloud Pub/Sub connector:
# Create a Pub/Sub topic and a subscription to that topic
# Publish a message to the topic and pull the message from the subscription
# Delete both the subscription and the topic
# Expected output: "SUCCESS"
- init:
    assign:
      - project: ${sys.get_env("GOOGLE_CLOUD_PROJECT_ID")}
      - topic: "TOPIC_ID"  # replace TOPIC_ID placeholder
      - subscription: "SUBSCRIPTION_ID"  # replace SUBSCRIPTION_ID placeholder
      - message: {"hello": "world"}
      - base64Msg: ${base64.encode(json.encode(message))}  # encodes bytes to Base64 text
- create_topic:
    call: googleapis.pubsub.v1.projects.topics.create
    args:
      name: ${"projects/" + project + "/topics/" + topic}
- create_subscription_to_topic:
    call: googleapis.pubsub.v1.projects.subscriptions.create
    args:
      name: ${"projects/" + project + "/subscriptions/" + subscription}
      body:
        name: ${"projects/" + project + "/subscriptions/" + subscription}
        topic: ${"projects/" + project + "/topics/" + topic}
- publish_message_to_topic:
    call: googleapis.pubsub.v1.projects.topics.publish
    args:
      topic: ${"projects/" + project + "/topics/" + topic}
      body:
        messages:
          - data: ${base64Msg}
- pull_message:
    call: googleapis.pubsub.v1.projects.subscriptions.pull
    args:
      subscription: ${"projects/" + project + "/subscriptions/" + subscription}
      body:
        maxMessages: 1
    result: m
- check_message:
    switch:
      - condition: ${m.receivedMessages[0].message.data != base64Msg}
        next: failed
- delete_subscription:
    call: googleapis.pubsub.v1.projects.subscriptions.delete
    args:
      subscription: ${"projects/" + project + "/subscriptions/" + subscription}
- delete_topic:
    call: googleapis.pubsub.v1.projects.topics.delete
    args:
      topic: ${"projects/" + project + "/topics/" + topic}
- the_end:
    return: "SUCCESS"
- failed:
    raise: ${"Received data:" + m.receivedMessages[0].message.data + " Expected data:" + base64Msg}

后续步骤

如需搜索和过滤其他 Google Cloud 产品的代码示例,请参阅 Google Cloud 示例浏览器