使用 gcloud CLI 在 Pub/Sub 中發布及接收訊息
本頁面說明如何使用 Google Cloud CLI,在 Pub/Sub 中執行下列作業:
- 建立主題和訂閱項目。
- 將訊息發布至主題。
- 接收訂閱項目的訊息。
如要直接在 Google Cloud 控制台中,按照這項工作的逐步指南操作,請按一下「Guide me」(逐步引導):
事前準備
請先完成下列步驟,再執行快速入門導覽課程。
設定專案
- 登入 Google Cloud 帳戶。如果您未曾使用過 Google Cloud,歡迎建立帳戶,親自體驗實際使用我們產品的成效。新客戶還能獲得價值 $300 美元的免費抵免額,用於執行、測試及部署工作負載。
Set up a Google Cloud console project.
Click to:
- Create or select a project.
- Enable the Pub/Sub API for that project, if it is not already enabled.
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, if it is not already enabled.
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
必要的角色
如要完成本快速入門導覽課程,您必須具備下列 Identity and Access Management (IAM) 角色。
如要取得完成本快速入門導覽課程所需的權限,請要求管理員在專案中授予您 Pub/Sub 編輯者 (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 會將訊息輸出至指令列。
還順利嗎?
後續步驟
查看 Pub/Sub 的所有可用 gcloud CLI 指令
進一步瞭解本頁討論的 Pub/Sub 概念。
閱讀 Pub/Sub 服務的基本概念。
實際練習 Pub/Sub 系統的端對端範例。
選擇訂閱類型。
進一步瞭解 Pub/Sub API。