使用 gcloud CLI 在 Pub/Sub 中發布及接收訊息
本頁面說明如何使用 Google Cloud CLI 在 Pub/Sub 中執行下列操作:
- 建立主題和訂閱項目。
- 將訊息發布至主題。
- 接收訂閱項目中的訊息。
如要直接在 Google Cloud 控制台按照逐步指南操作,請按一下「Guide me」(逐步引導):
事前準備
- 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.
-
Set up a Google 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 Google Cloud console.
-
Install the Google Cloud CLI.
-
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
-
To initialize the gcloud CLI, run the following command:
gcloud init
-
Set up a Google 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 Google Cloud console.
-
Install the Google Cloud CLI.
-
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
-
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 會將訊息輸出至指令列。
還順利嗎?
後續步驟
查看 Pub/Sub 適用的所有可用 gCloud CLI 指令
進一步瞭解本頁討論的 Pub/Sub 概念。
閱讀 Pub/Sub 服務的基本概念。
實際練習 Pub/Sub 系統的端對端範例。
選擇訂閱類型。
進一步瞭解 Pub/Sub API。