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

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

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

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

操作演示


准备工作

在运行流水线之前,请完成以下步骤。

设置项目

  1. Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
  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. 如果您使用的是外部身份提供方 (IdP),则必须先使用联合身份登录 gcloud CLI

  5. 如需初始化 gcloud CLI,请运行以下命令:

    gcloud init
  6. 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.

  7. Install the Google Cloud CLI.

  8. 如果您使用的是外部身份提供方 (IdP),则必须先使用联合身份登录 gcloud CLI

  9. 如需初始化 gcloud CLI,请运行以下命令:

    gcloud init
  10. 所需的角色

    如需完成本快速入门,您需要拥有以下 Identity and Access Management (IAM) 角色。

    如需获得完成本快速入门所需的权限,请让您的管理员为您授予项目的 Pub/Sub Editor (roles/pubsub.editor) IAM 角色。 如需详细了解如何授予角色,请参阅管理对项目、文件夹和组织的访问权限

    您也可以通过自定义角色或其他预定义角色来获取所需的权限。

    创建主题

    创建 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 会将消息输出到命令行。

    结果怎么样?

    后续步骤