Publish message to Google Pub/Sub topic using Spring Cloud GCP PubSub

In the previous post, I showed you how to publish messages to Google Pub/Sub topic using the Pub/Sub client library. Using the Spring Cloud GCP PubSub library will help us do this much simpler. How is it in detail? In this tutorial, I will show you how to publish messages to Google Pub/Sub topic using Spring Cloud GCP PubSub.

First, I will create a new Spring Boot project with GCP Messaging dependency:

for example.

Result:

The first thing I need to tell you is that Spring Cloud GCP PubSub provides us with an interface called PubSubOperations to work with Google Pub/Sub.

The implementation of this interface is the PubSubTemplate class and behind the sense, this PubSubTemplate class also uses the Google PubSub client library to work with Google Pub/Sub.

Using Spring Cloud GCP Starter PubSub will help us reduce configuration steps to be able to work with Google Pub/Sub more easily.

As an example, I will implement the CommandLineRunner interface for the SpringGcpPubsubPublishApplication class to run a Spring Boot application with the Java console as follows:

Now we just need to inject the object of the PubSubTemplate class and use the publish() method of this object to publish the message.

There are multiple overloading methods for this publish() method. I will use the publish() method with 2 parameters in order, the topic ID and the PubSubMessage object of the Google PubSub client library, specifically as follows:

As you can see, Spring Cloud GCP PubSub uses a different interface to get the result of publishing, the ListenableFuture message. This interface also extends from Java’s Future interface! And we also don’t need to pass project ID information in this case.

For the authentication part with GCP Pub/Sub, in addition to using the GOOGLE_APPLICATION_CREDENTIALS environment variable, Spring Boot supports us with another property called spring.cloud.gcp.credentials.location.

You just need to configure this property with the value pointing to the Service Account key file!

In this case, you need to configure more project ID information:

In the example of this tutorial, I will run the project with the environment variable GOOGLE_APPLICATION_CREDENTIALS:

Check Google Pub/Sub topic, you will see the following results:

Add Comment