使用 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. 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.

    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

建立主題

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

還順利嗎?

後續步驟