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:
Before you begin
- 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.
-
Set up a Google Cloud console 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.
- Install the Google Cloud CLI.
-
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.
You can view and manage these resources at any time in the Google Cloud console.
- Install the Google Cloud CLI.
-
To initialize the gcloud CLI, run the following command:
gcloud init
Create a topic
Create a topic with the ID my-topic
:
gcloud pubsub topics create my-topic
Create a subscription
Create a subscription with the ID my-sub
and attach it to my-topic
:
gcloud pubsub subscriptions create my-sub --topic=my-topic
Publish messages
Publish a message to my-topic
:
gcloud pubsub topics publish my-topic --message="hello"
Receive messages
Receive the message from my-sub
:
gcloud pubsub subscriptions pull my-sub --auto-ack
The gcloud CLI prints the message to the command line.
How did it go?
What's next
See all the available gCloud CLI commands for Pub/Sub
Learn more about the Pub/Sub concepts discussed in this page.
Read the basics of the Pub/Sub service.
Work through an end-to-end example of a Pub/Sub system.
Try another Pub/Sub quickstart that uses client libraries or the console.
Choose a subscription type.
Learn more about Pub/Sub APIs.