使用 gcloud CLI 在 Pub/Sub 中發布及接收訊息

本頁面說明如何使用 Google Cloud CLI 在 Pub/Sub 中執行下列作業:

  • 建立主題和訂閱項目。
  • 將訊息發布至主題。
  • 接收訂閱項目中的訊息。

如要直接在 Google Cloud 控制台中,按照這項工作的逐步指南操作,請按一下「Guide me」(逐步引導):

「Guide me」(逐步引導)


事前準備

請先完成下列步驟,再執行快速入門。

設定專案

  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, if it is not already enabled.

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

  3. Install the Google Cloud CLI.

  4. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

  5. To initialize the gcloud CLI, run the following command:

    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, if it is not already enabled.

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

  7. Install the Google Cloud CLI.

  8. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

  9. 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 會在指令列中列印訊息。

還順利嗎?

後續步驟