使用 gcloud CLI 在 Pub/Sub 中发布和接收消息
本页面介绍如何使用 Google Cloud CLI 在 Pub/Sub 中执行以下操作:
- 创建主题和订阅
- 将消息发布到主题。
- 接收来自订阅的消息。
准备工作
-
Set up a Trusted Cloud console 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 Trusted Cloud console.
-
Install the Google Cloud CLI.
-
配置 gcloud CLI 以使用您的联合身份。
如需了解详情,请参阅 使用联合身份登录 gcloud CLI。
-
如需初始化 gcloud CLI,请运行以下命令:
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 会将消息输出到命令行。
结果怎么样?
后续步骤
查看适用于 Pub/Sub 的所有可用 gCloud CLI 命令
详细了解本页面中讨论的 Pub/Sub 概念。
阅读 Pub/Sub 服务的基础知识。
完成 Pub/Sub 系统的端到端示例。
选择订阅类型。
详细了解 Pub/Sub API。