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

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

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

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

逐步引導


事前準備

  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. 建立主題

    使用 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 會在指令列輸出訊息。

    還順利嗎?

    後續步驟