Publish and receive messages in Pub/Sub by using the gcloud CLI

This page shows you how to do the following operations in Pub/Sub using the Google Cloud CLI:

  • Create a topic and subscription.
  • Publish messages to the topic.
  • Receive messages from the subscription.

To follow step-by-step guidance for this task directly in the Google Cloud console, click Guide me:

Guide me


Before you begin

  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:

    gcloudinit
  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:

    gcloudinit

Create a topic

Create a topic with the ID my-topic:

gcloudpubsubtopicscreatemy-topic

Create a subscription

Create a subscription with the ID my-sub and attach it to my-topic:

gcloudpubsubsubscriptionscreatemy-sub--topic=my-topic

Publish messages

Publish a message to my-topic:

gcloudpubsubtopicspublishmy-topic--message="hello"

Receive messages

Receive the message from my-sub:

gcloudpubsubsubscriptionspullmy-sub--auto-ack

The gcloud CLI prints the message to the command line.

How did it go?

What's next

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2025年10月24日 UTC.