Subscribe to Google Pub/Sub topic with Spring Cloud GCP PubSub

In the previous post, I showed you how to publish a message to Google Pub/Sub topic using Spring Cloud GCP PubSub? In this tutorial, let’s learn together how to subscribe to it to receive messages with Spring Cloud GCP PubSub!

I also created a Spring Boot with GCP Message dependency as follows:


I will also implement the CommandLineRunner interface for the SpringGcpPubsubSubscribeApplication class as follows:

To subscribe to and receive messages from the GCP Pub/Sub topic, we also inject the PubSubTemplate class and use the subscribe() method of this object.

The parameter of this subscribe() method is, respectively, the subscription name associated with the topic and a Consumer object with the type of BasicAcknowledgeablePubsubMessage to consume the message, specifically as follows:

The data received from the GCP Pub/Sub topic is a PubsubMessage object of the PubSub client library. You can get the exact message content after getData() and call the toStringUtf8() method as I did above.

For the authentication part with GCP Pub/Sub, I will use the property with the property, as follows:

Result when I publish a message on Google Pub/Sub topic:

as follows:

Normally, after receiving and processing the message from the GCP Pub/Sub topic, without any errors, we will send an acknowledgment for the GCP Pub/Sub topic to delete the message. You can call the ack() method of the BasicAcknowledgeablePubsubMessage object to do this, as follows:

Now, if you run the example again, you will see that the message that we publish to the topic is only consumed and printed once instead of the two times above:

Add Comment