使用 gcloud CLI 在 Pub/Sub 中发布和接收消息

本页面介绍如何使用 Google Cloud CLI 在 Pub/Sub 中执行以下操作:

  • 创建主题和订阅
  • 将消息发布到主题。
  • 接收来自订阅的消息。

如需在 Google Cloud 控制台中直接遵循有关此任务的分步指导,请点击操作演示

操作演示


准备工作

  1. 登录您的 Google Cloud 账号。如果您是 Google Cloud 新手,请创建一个账号来评估我们的产品在实际场景中的表现。新客户还可获享 $300 赠金,用于运行、测试和部署工作负载。
  2. Set up a Google Cloud console project.

    Set up a project

    Click to:

    • Create or select a project.
    • Enable the Pub/Sub API for that project.

    You can view and manage these resources at any time in the Google Cloud console.

  3. Install the Google Cloud CLI.
  4. To initialize the gcloud CLI, run the following command:

    gcloud init
  5. Set up a Google Cloud console project.

    Set up a project

    Click to:

    • Create or select a project.
    • Enable the Pub/Sub API for that project.

    You can view and manage these resources at any time in the Google Cloud console.

  6. Install the Google Cloud CLI.
  7. To initialize the gcloud CLI, run the following command:

    gcloud init

创建主题

创建 ID 为 my-topic 的主题:

gcloud pubsub topics create my-topic

创建订阅

创建 ID 为 my-sub 的订阅,并将其附加到 my-topic

gcloud pubsub subscriptions create my-sub --topic=my-topic

发布消息

将消息发布到 my-topic

gcloud pubsub topics publish my-topic --message="hello"

接收消息

接收来自 my-sub 的消息:

gcloud pubsub subscriptions pull my-sub --auto-ack

gcloud CLI 会将消息输出到命令行。

结果怎么样?

后续步骤