Publish message to Google Pub/Sub topic using Pub/Sub Java client library

Google Pub/Sub is one of the cloud messaging services that we can use if your application has features that require using messaging technology. In this article, I will show you how to publish a message to Google Pub/Sub topic using the Pub/Sub Java client library!

First, I will create a new Maven project:

for example.

The Google Pub/Sub client dependency is as follows:

I will create a new class with main() method as an example:

As an example, I will also create a new topic on Google Pub/Sub with the following information about the project ID and topic ID:

To start, we will declare this information in the code as follows:

To publish a message to a topic, we need the TopicName object of the Google Pub/Sub client library. You initialize this object from the project ID and topic ID as follows:

After we have the TopicName, we will initialize the Publisher object to prepare to publish the message:

The publish() method of the Publisher object will help us to publish the message. The parameter of this method is a PubsubMessage object, created from the message we want to publish as follows:

Now you can publish messages:

The entire code is as follows:

Here, as you can see, I also added code to get the result of whether the message publishing was successful or not? Using Google Pub/Sub’s ApiFuture interface extends from Java’s Future interface.

Before running this example, we need to do one more step to configure the authentication for the application with Google Pub/Sub.

Google Pub/Sub supports us with 2 types of authentication: using Service Account or Access Control with IAM. Usually, we will use Service Account to do this.

You can use a Service Account with Role Pub/Sub Admin to publish messages to Pub/Sub topic as follows:

There is another Role, Pub/Sub Publisher, just to publish messages, but I don’t understand why it doesn’t work, can’t send messages with this Role. If you know the reason, please share!

After adding the key for this Service Account with type JSON or P12, this private key file will be saved to your computer.

You just need to set an environment variable in your machine or in the application configuration section of the IDE with the name GOOGLE_APPLICATION_CREDENTIALS. The value of this environment variable points to the path of the above private key file.

My example is as follows:

Now if you run the application and check the topic, you will see the following results:

As you can see, a message has been published to our topic!

Add Comment