Publish and receive messages in Pub/Sub by using a client library
The Pub/Sub service allows applications to exchange messages reliably,quickly, and asynchronously. The following is the sequence of events:
- A producer of data publishes a message to a Pub/Sub topic.
- A subscriber client creates a subscription to that topic and consumesmessages from the subscription.
You can set up a Pub/Sub environment by using any of thefollowing methods: Google Cloud console, Cloud Shell, client libraries, orREST APIs. This page shows you how to get started publishing messages withPub/Sub using client libraries.
Pub/Sub offers a high-level and a low-level auto-generatedclient library. By default, as in this quickstart,we recommend the high-level client library.
To follow step-by-step guidance for this task directly in the Google Cloud console, clickGuide 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.
Install the Google Cloud CLI.
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
Toinitialize the gcloud CLI, run the following command:
gcloudinit
Create or select a Google Cloud project.
Note: If you don't plan to keep the resources that you create in this procedure, create a project instead of selecting an existing project. After you finish these steps, you can delete the project, removing all resources associated with the project.Roles required to select or create a project
- Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
- Create a project: To create a project, you need the Project Creator role (
roles/resourcemanager.projectCreator), which contains theresourcemanager.projects.createpermission.Learn how to grant roles.
Create a Google Cloud project:
gcloud projects createPROJECT_ID
Replace
PROJECT_IDwith a name for the Google Cloud project you are creating.Select the Google Cloud project that you created:
gcloud config set projectPROJECT_ID
Replace
PROJECT_IDwith your Google Cloud project name.
Verify that billing is enabled for your Google Cloud project.
Enable the Pub/Sub API:
Roles required to enable APIs
To enable APIs, you need the Service Usage Admin IAM role (
roles/serviceusage.serviceUsageAdmin), which contains theserviceusage.services.enablepermission.Learn how to grant roles.gcloudservicesenablepubsub.googleapis.comCreate local authentication credentials for your user account:
gcloudauthapplication-defaultlogin
Note: If the gcloud CLI prints a warning that your account doesn't have the
serviceusage.services.usepermission, then some gcloud CLI commands and client libraries might not work. Ask an administrator to grant you the Service Usage Consumer IAM role (roles/serviceusage.serviceUsageConsumer), then run the following command:gcloudauthapplication-defaultset-quota-projectPROJECT_ID
If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.
Grant roles to your user account. Run the following command once for each of the following IAM roles:
roles/pubsub.admingcloudprojectsadd-iam-policy-bindingPROJECT_ID--member="user:USER_IDENTIFIER"--role=ROLE
Replace the following:
PROJECT_ID: Your project ID.USER_IDENTIFIER: The identifier for your user account. For example,myemail@example.com.ROLE: The IAM role that you grant to your user account.
Install the Google Cloud CLI.
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
Toinitialize the gcloud CLI, run the following command:
gcloudinit
Create or select a Google Cloud project.
Note: If you don't plan to keep the resources that you create in this procedure, create a project instead of selecting an existing project. After you finish these steps, you can delete the project, removing all resources associated with the project.Roles required to select or create a project
- Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
- Create a project: To create a project, you need the Project Creator role (
roles/resourcemanager.projectCreator), which contains theresourcemanager.projects.createpermission.Learn how to grant roles.
Create a Google Cloud project:
gcloud projects createPROJECT_ID
Replace
PROJECT_IDwith a name for the Google Cloud project you are creating.Select the Google Cloud project that you created:
gcloud config set projectPROJECT_ID
Replace
PROJECT_IDwith your Google Cloud project name.
Verify that billing is enabled for your Google Cloud project.
Enable the Pub/Sub API:
Roles required to enable APIs
To enable APIs, you need the Service Usage Admin IAM role (
roles/serviceusage.serviceUsageAdmin), which contains theserviceusage.services.enablepermission.Learn how to grant roles.gcloudservicesenablepubsub.googleapis.comCreate local authentication credentials for your user account:
gcloudauthapplication-defaultlogin
Note: If the gcloud CLI prints a warning that your account doesn't have the
serviceusage.services.usepermission, then some gcloud CLI commands and client libraries might not work. Ask an administrator to grant you the Service Usage Consumer IAM role (roles/serviceusage.serviceUsageConsumer), then run the following command:gcloudauthapplication-defaultset-quota-projectPROJECT_ID
If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.
Grant roles to your user account. Run the following command once for each of the following IAM roles:
roles/pubsub.admingcloudprojectsadd-iam-policy-bindingPROJECT_ID--member="user:USER_IDENTIFIER"--role=ROLE
Replace the following:
PROJECT_ID: Your project ID.USER_IDENTIFIER: The identifier for your user account. For example,myemail@example.com.ROLE: The IAM role that you grant to your user account.
Install the client libraries
The following samples show you how to install the client libraries:
Python
For more on setting up your Python development environment, refer toPython Development Environment Setup Guide.
# ensure that you are using virtualenv
# as described in the python dev setup guide
pip install --upgrade google-cloud-pubsub
C++
For more information about installing the C++ library,see theGitHubREADME
C#
Install-Package Google.Cloud.PubSub.V1 -Pre
Go
go get cloud.google.com/go/pubsub
Java
If you are usingMaven, addthe following to yourpom.xml file. For more information aboutBOMs, seeThe Google Cloud Platform Libraries BOM.
<dependencyManagement> <dependencies> <dependency> <groupId>com.google.cloud</groupId> <artifactId>libraries-bom</artifactId> <version>26.74.0</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies></dependencyManagement><dependencies> <dependency> <groupId>com.google.cloud</groupId> <artifactId>google-cloud-pubsub</artifactId> </dependency></dependencies>If you are usingGradle,add the following to your dependencies:
implementation platform('com.google.cloud:libraries-bom:26.74.0')implementation 'com.google.cloud:google-cloud-pubsub'If you are usingsbt, addthe following to your dependencies:
libraryDependencies += "com.google.cloud" % "google-cloud-pubsub" % "1.148.0"If you're using Visual Studio Code or IntelliJ, you can add client libraries to your project using the following IDE plugins:
The plugins provide additional functionality, such as key management for service accounts. Refer to each plugin's documentation for details.
Note: Cloud Java client libraries do not currently support Android.Node.js
npm install @google-cloud/pubsub
PHP
composer require google/cloud-pubsub
Ruby
gem install google-cloud-pubsub
Create a topic and a subscription
After you create a topic, you can subscribe or publish to it.
Use the followinggcloud pubsub topics create command to create a topic namedmy-topic. Don't change the name of the topic, because it's referenced throughout the rest of the tutorial.
gcloudpubsubtopicscreatemy-topic
Use thegcloud pubsub subscriptions create command to create a subscription. Only messages publishedto the topic after the subscription is created are available to subscriberapplications.
gcloudpubsubsubscriptionscreatemy-sub--topicmy-topic
400 Invalid resource name given, yourresource name contains an invalid character. For more information about namingyour topics and subscriptions, seeResourcenames.Publish messages
Before running the following samples, make sure you uncomment and fill in any ofthe required values that are marked in the code. This is required to link thesample to your project and Pub/Sub resources that you createdearlier.
Usemy-topic for your topic ID.
Python
fromgoogle.cloudimportpubsub_v1# TODO(developer)# project_id = "your-project-id"# topic_id = "your-topic-id"publisher=pubsub_v1.PublisherClient()# The `topic_path` method creates a fully qualified identifier# in the form `projects/{project_id}/topics/{topic_id}`topic_path=publisher.topic_path(project_id,topic_id)forninrange(1,10):data_str=f"Message number{n}"# Data must be a bytestringdata=data_str.encode("utf-8")# When you publish a message, the client returns a future.future=publisher.publish(topic_path,data)print(future.result())print(f"Published messages to{topic_path}.")C++
#include"google/cloud/pubsub/publisher.h"#include <iostream>intmain(intargc,char*argv[])try{if(argc!=3){std::cerr <<"Usage: " <<argv[0] <<" <project-id> <topic-id>\n";return1;}std::stringconstproject_id=argv[1];std::stringconsttopic_id=argv[2];// Create a namespace alias to make the code easier to read.namespacepubsub=::google::cloud::pubsub;autopublisher=pubsub::Publisher(pubsub::MakePublisherConnection(pubsub::Topic(project_id,topic_id)));autoid=publisher.Publish(pubsub::MessageBuilder{}.SetData("Hello World!").Build()).get();if(!id)throwstd::move(id).status();std::cout <<"Hello World published withdevsite-syntax-w"> <<*id <<"\n";return0;}catch(google::cloud::Statusconst&status){std::cerr <<"google::cloud::Status thrown: " <<status <<"\n";return1;}C#
usingGoogle.Cloud.PubSub.V1;usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Threading;usingSystem.Threading.Tasks;publicclassPublishMessagesAsyncSample{publicasyncTask<int>PublishMessagesAsync(stringprojectId,stringtopicId,IEnumerable<string>messageTexts){TopicNametopicName=TopicName.FromProjectTopic(projectId,topicId);PublisherClientpublisher=awaitPublisherClient.CreateAsync(topicName);intpublishedMessageCount=0;varpublishTasks=messageTexts.Select(asynctext=>{try{stringmessage=awaitpublisher.PublishAsync(text);Console.WriteLine($"Published message {message}");Interlocked.Increment(refpublishedMessageCount);}catch(Exceptionexception){Console.WriteLine($"An error occurred when publishing message {text}: {exception.Message}");}});awaitTask.WhenAll(publishTasks);// PublisherClient instance should be shutdown after use.// The TimeSpan specifies for how long to attempt to publish locally queued messages.awaitpublisher.ShutdownAsync(TimeSpan.FromSeconds(15));returnpublishedMessageCount;}}Go
import("context""fmt""io""cloud.google.com/go/pubsub/v2")funcpublish(wio.Writer,projectID,topicID,msgstring)error{// projectID := "my-project-id"// topicID := "my-topic"// msg := "Hello World"ctx:=context.Background()client,err:=pubsub.NewClient(ctx,projectID)iferr!=nil{returnfmt.Errorf("pubsub: NewClient: %w",err)}deferclient.Close()// client.Publisher can be passed a topic ID (e.g. "my-topic") or// a fully qualified name (e.g. "projects/my-project/topics/my-topic").// If a topic ID is provided, the project ID from the client is used.// Reuse this publisher for all publish calls to send messages in batches.publisher:=client.Publisher(topicID)result:=publisher.Publish(ctx,&pubsub.Message{Data:[]byte(msg),})// Block until the result is returned and a server-generated// ID is returned for the published message.id,err:=result.Get(ctx)iferr!=nil{returnfmt.Errorf("pubsub: result.Get: %w",err)}fmt.Fprintf(w,"Published a message; msg ID: %v\n",id)returnnil}Java
importcom.google.api.core.ApiFuture;importcom.google.cloud.pubsub.v1.Publisher;importcom.google.protobuf.ByteString;importcom.google.pubsub.v1.PubsubMessage;importcom.google.pubsub.v1.TopicName;importjava.io.IOException;importjava.util.concurrent.ExecutionException;importjava.util.concurrent.TimeUnit;publicclassPublisherExample{publicstaticvoidmain(String...args)throwsException{// TODO(developer): Replace these variables before running the sample.StringprojectId="your-project-id";StringtopicId="your-topic-id";publisherExample(projectId,topicId);}publicstaticvoidpublisherExample(StringprojectId,StringtopicId)throwsIOException,ExecutionException,InterruptedException{TopicNametopicName=TopicName.of(projectId,topicId);Publisherpublisher=null;try{// Create a publisher instance with default settings bound to the topicpublisher=Publisher.newBuilder(topicName).build();Stringmessage="Hello World!";ByteStringdata=ByteString.copyFromUtf8(message);PubsubMessagepubsubMessage=PubsubMessage.newBuilder().setData(data).build();// Once published, returns a server-assigned message id (unique within the topic)ApiFuture<String>messageIdFuture=publisher.publish(pubsubMessage);StringmessageId=messageIdFuture.get();System.out.println("Published message ID: "+messageId);}finally{if(publisher!=null){// When finished with the publisher, shutdown to free up resources.publisher.shutdown();publisher.awaitTermination(1,TimeUnit.MINUTES);}}}}Node.js
/** * TODO(developer): Uncomment these variables before running the sample. */// const topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID';// const data = JSON.stringify({foo: 'bar'});// Imports the Google Cloud client libraryconst{PubSub}=require('@google-cloud/pubsub');// Creates a client; cache this for further useconstpubSubClient=newPubSub();asyncfunctionpublishMessage(topicNameOrId,data){// Publishes the message as a string, e.g. "Hello, world!" or JSON.stringify(someObject)constdataBuffer=Buffer.from(data);// Cache topic objects (publishers) and reuse them.consttopic=pubSubClient.topic(topicNameOrId);try{constmessageId=awaittopic.publishMessage({data:dataBuffer});console.log(`Message${messageId} published.`);}catch(error){console.error(`Received error while publishing:${error.message}`);process.exitCode=1;}}Node.js
/** * TODO(developer): Uncomment these variables before running the sample. */// const topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID';// const data = JSON.stringify({foo: 'bar'});// Imports the Google Cloud client libraryimport{PubSub}from'@google-cloud/pubsub';// Creates a client; cache this for further useconstpubSubClient=newPubSub();asyncfunctionpublishMessage(topicNameOrId:string,data:string){// Publishes the message as a string, e.g. "Hello, world!" or JSON.stringify(someObject)constdataBuffer=Buffer.from(data);// Cache topic objects (publishers) and reuse them.consttopic=pubSubClient.topic(topicNameOrId);try{constmessageId=awaittopic.publishMessage({data:dataBuffer});console.log(`Message${messageId} published.`);}catch(error){console.error(`Received error while publishing:${(errorasError).message}`,);process.exitCode=1;}}PHP
use Google\Cloud\PubSub\MessageBuilder;use Google\Cloud\PubSub\PubSubClient;/** * Publishes a message for a Pub/Sub topic. * * @param string $projectId The Google project ID. * @param string $topicName The Pub/Sub topic name. * @param string $message The message to publish. */function publish_message($projectId, $topicName, $message){ $pubsub = new PubSubClient([ 'projectId' => $projectId, ]); $topic = $pubsub->topic($topicName); $topic->publish((new MessageBuilder)->setData($message)->build()); print('Message published' . PHP_EOL);}Ruby
Receive messages
Set up a subscriber to pull the messages you just published. Every subscribermust acknowledge each message within a configurable time window. Unacknowledgedmessages are redelivered. Note that Pub/Sub occasionallydelivers a message more than once to ensure that all messages make it to asubscriber at least once.
Before running the following samples, make sure you uncomment and fill in any ofthe required values that are marked in the code. This is required to link thesample to your project and Pub/Sub resources that you createdearlier
Usemy-sub for your subscription ID.
For more examples that show how to pull messages, seeClient Library code samples.
Python
fromconcurrent.futuresimportTimeoutErrorfromgoogle.cloudimportpubsub_v1# TODO(developer)# project_id = "your-project-id"# subscription_id = "your-subscription-id"# Number of seconds the subscriber should listen for messages# timeout = 5.0subscriber=pubsub_v1.SubscriberClient()# The `subscription_path` method creates a fully qualified identifier# in the form `projects/{project_id}/subscriptions/{subscription_id}`subscription_path=subscriber.subscription_path(project_id,subscription_id)defcallback(message:pubsub_v1.subscriber.message.Message)->None:print(f"Received{message}.")message.ack()streaming_pull_future=subscriber.subscribe(subscription_path,callback=callback)print(f"Listening for messages on{subscription_path}..\n")# Wrap subscriber in a 'with' block to automatically call close() when done.withsubscriber:try:# When `timeout` is not set, result() will block indefinitely,# unless an exception is encountered first.streaming_pull_future.result(timeout=timeout)exceptTimeoutError:streaming_pull_future.cancel()# Trigger the shutdown.streaming_pull_future.result()# Block until the shutdown is complete.C++
#include"google/cloud/pubsub/message.h"#include"google/cloud/pubsub/subscriber.h"#include <iostream>intmain(intargc,char*argv[])try{if(argc!=3){std::cerr <<"Usage: " <<argv[0] <<" <project-id> <subscription-id>\n";return1;}std::stringconstproject_id=argv[1];std::stringconstsubscription_id=argv[2];autoconstexprkWaitTimeout=std::chrono::seconds(30);// Create a namespace alias to make the code easier to read.namespacepubsub=::google::cloud::pubsub;autosubscriber=pubsub::Subscriber(pubsub::MakeSubscriberConnection(pubsub::Subscription(project_id,subscription_id)));autosession=subscriber.Subscribe([&](pubsub::Messageconst&m,pubsub::AckHandlerh){std::cout <<"Received message " <<m <<"\n";std::move(h).ack();});std::cout <<"Waiting for messages on "+subscription_id+"...\n";// Blocks until the timeout is reached.autoresult=session.wait_for(kWaitTimeout);if(result==std::future_status::timeout){std::cout <<"timeout reached, ending session\n";session.cancel();}return0;}catch(google::cloud::Statusconst&status){std::cerr <<"google::cloud::Status thrown: " <<status <<"\n";return1;}C#
usingGoogle.Cloud.PubSub.V1;usingSystem;usingSystem.Threading;usingSystem.Threading.Tasks;publicclassPullMessagesAsyncSample{publicasyncTask<int>PullMessagesAsync(stringprojectId,stringsubscriptionId,boolacknowledge){SubscriptionNamesubscriptionName=SubscriptionName.FromProjectSubscription(projectId,subscriptionId);SubscriberClientsubscriber=awaitSubscriberClient.CreateAsync(subscriptionName);// SubscriberClient runs your message handle function on multiple// threads to maximize throughput.intmessageCount=0;TaskstartTask=subscriber.StartAsync((PubsubMessagemessage,CancellationTokencancel)=>{stringtext=message.Data.ToStringUtf8();Console.WriteLine($"Message {message.MessageId}: {text}");Interlocked.Increment(refmessageCount);returnTask.FromResult(acknowledge?SubscriberClient.Reply.Ack:SubscriberClient.Reply.Nack);});// Run for 5 seconds.awaitTask.Delay(5000);awaitsubscriber.StopAsync(CancellationToken.None);// Lets make sure that the start task finished successfully after the call to stop.awaitstartTask;returnmessageCount;}}Go
import("context""fmt""io""sync/atomic""time""cloud.google.com/go/pubsub/v2")funcpullMsgs(wio.Writer,projectID,subIDstring)error{// projectID := "my-project-id"// subID := "my-sub"ctx:=context.Background()client,err:=pubsub.NewClient(ctx,projectID)iferr!=nil{returnfmt.Errorf("pubsub.NewClient: %w",err)}deferclient.Close()// client.Subscriber can be passed a subscription ID (e.g. "my-sub") or// a fully qualified name (e.g. "projects/my-project/subscriptions/my-sub").// If a subscription ID is provided, the project ID from the client is used.sub:=client.Subscriber(subID)// Receive messages for 10 seconds, which simplifies testing.// Comment this out in production, since `Receive` should// be used as a long running operation.ctx,cancel:=context.WithTimeout(ctx,10*time.Second)defercancel()varreceivedint32err=sub.Receive(ctx,func(_context.Context,msg*pubsub.Message){fmt.Fprintf(w,"Got message: %q\n",string(msg.Data))atomic.AddInt32(&received,1)msg.Ack()})iferr!=nil{returnfmt.Errorf("sub.Receive: %w",err)}fmt.Fprintf(w,"Received %d messages\n",received)returnnil}Java
importcom.google.cloud.pubsub.v1.AckReplyConsumer;importcom.google.cloud.pubsub.v1.MessageReceiver;importcom.google.cloud.pubsub.v1.Subscriber;importcom.google.pubsub.v1.ProjectSubscriptionName;importcom.google.pubsub.v1.PubsubMessage;importjava.util.concurrent.TimeUnit;importjava.util.concurrent.TimeoutException;publicclassSubscribeAsyncExample{publicstaticvoidmain(String...args)throwsException{// TODO(developer): Replace these variables before running the sample.StringprojectId="your-project-id";StringsubscriptionId="your-subscription-id";subscribeAsyncExample(projectId,subscriptionId);}publicstaticvoidsubscribeAsyncExample(StringprojectId,StringsubscriptionId){ProjectSubscriptionNamesubscriptionName=ProjectSubscriptionName.of(projectId,subscriptionId);// Instantiate an asynchronous message receiver.MessageReceiverreceiver=(PubsubMessagemessage,AckReplyConsumerconsumer)->{// Handle incoming message, then ack the received message.System.out.println("Id: "+message.getMessageId());System.out.println("Data: "+message.getData().toStringUtf8());consumer.ack();};Subscribersubscriber=null;try{subscriber=Subscriber.newBuilder(subscriptionName,receiver).build();// Start the subscriber.subscriber.startAsync().awaitRunning();System.out.printf("Listening for messages on %s:\n",subscriptionName.toString());// Allow the subscriber to run for 30s unless an unrecoverable error occurs.subscriber.awaitTerminated(30,TimeUnit.SECONDS);}catch(TimeoutExceptiontimeoutException){// Shut down the subscriber after 30s. Stop receiving messages.subscriber.stopAsync();}}}Node.js
/** * TODO(developer): Uncomment these variables before running the sample. */// const subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID';// const timeout = 60;// Imports the Google Cloud client libraryconst{PubSub}=require('@google-cloud/pubsub');// Creates a client; cache this for further useconstpubSubClient=newPubSub();functionlistenForMessages(subscriptionNameOrId,timeout){// References an existing subscription; if you are unsure if the// subscription will exist, try the optimisticSubscribe sample.constsubscription=pubSubClient.subscription(subscriptionNameOrId);// Create an event handler to handle messagesletmessageCount=0;constmessageHandler=message=>{console.log(`Received message${message.id}:`);console.log(`\tData:${message.data}`);console.log(`\tAttributes:${message.attributes}`);messageCount+=1;// "Ack" (acknowledge receipt of) the messagemessage.ack();};// Listen for new messages until timeout is hitsubscription.on('message',messageHandler);// Wait a while for the subscription to run. (Part of the sample only.)setTimeout(()=>{subscription.removeListener('message',messageHandler);console.log(`${messageCount} message(s) received.`);},timeout*1000);}PHP
use Google\Cloud\PubSub\PubSubClient;/** * Pulls all Pub/Sub messages for a subscription. * * @param string $projectId The Google project ID. * @param string $subscriptionName The Pub/Sub subscription name. */function pull_messages($projectId, $subscriptionName){ $pubsub = new PubSubClient([ 'projectId' => $projectId, ]); $subscription = $pubsub->subscription($subscriptionName); foreach ($subscription->pull() as $message) { printf('Message: %s' . PHP_EOL, $message->data()); // Acknowledge the Pub/Sub message has been received, so it will not be pulled multiple times. $subscription->acknowledge($message); }}Ruby
# subscription_id = "your-subscription-id"pubsub=Google::Cloud::PubSub.newsubscriber=pubsub.subscribersubscription_idlistener=subscriber.listendo|received_message|puts"Received message:#{received_message.data}"received_message.acknowledge!endlistener.start# Let the main thread sleep for 60 seconds so the thread for listening# messages does not quitsleep60listener.stop.wait!How did it go?
Clean up (optional)
- To avoid incurring charges to your Google Cloud account for theresources used in this guide, you can use thecommand line to delete the topic and subscription.
gcloudpubsubsubscriptionsdeletemy-subgcloudpubsubtopicsdeletemy-topic
Optional: Revoke the authentication credentials that you created, and delete the local credential file.
gcloudauthapplication-defaultrevoke
Optional: Revoke credentials from the gcloud CLI.
gcloudauthrevoke
What's next
Learn more about the Pub/Subconcepts discussed in this page.
Read thebasics of the Pub/Sub service.
Learn how tobuild a one-to-many Pub/Sub system, which creates a publisher application that publishes to two separate subscriber applications.
Try another Pub/Sub quickstart thatuses thegcloud CLI or theconsole.
Learn more aboutPub/Sub APIs.
Learn how to run Pub/Sub usingKotlin.
Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2026-02-19 UTC.