Google Pub/Sub is a robust, fully managed service that enables real-time messaging between applications. However, when integrating Pub/Sub into your Spring applications, you might not want to deal with the specifics of the Pub/Sub API directly. This is where the Spring Cloud GCP library comes into play.
Spring Cloud GCP provides a channel adapter for Spring Integration, allowing Pub/Sub to be used as a message channel in your application. What this means is that you can interact with Pub/Sub using familiar Spring Integration paradigms, effectively abstracting away the underlying Pub/Sub API details. The beauty of this approach lies in its flexibility—while your application benefits from Pub/Sub, it isn’t tightly coupled to it. This makes your code more portable and easier to maintain.
In practical terms, you can leverage the @ServiceActivator annotation from Spring Integration to define a method that will act as a message handler. This method is triggered when a message arrives on the subscribed channel.
For instance, if you have a Pub/Sub topic named factchanged, the name of this topic can be supplied by an environment variable (pubsub.topic.factchanged). This environment variable is set in the env.yaml file used during the Cloud Run deployment.
Here, a MessageHandler bean is being defined, which will handle outgoing messages to the Pub/Sub service. The @ServiceActivator annotation is used to specify that this handler will be listening on the pubsubOutputChannel for any messages.
The MessageHandler is configured with a PubSubTemplate, which is a helper class provided by the Spring Cloud GCP library to interact with Pub/Sub. The topic to which the messages will be sent is set to the value of the pubsub.topic.factchanged environment variable.
Additionally, a PubsubOutboundGateway interface is defined. This interface is marked with the @MessagingGateway annotation, which indicates it’s a gateway to the messaging system. The method sendToPubsub(String payload) will send a message to the pubsubOutputChannel, effectively pushing the message to the configured Pub/Sub topic.
In the code then, you can use the PubsubOutboundGateway to send a message to Pub/Sub. For example, following is the code added to the FactController to send a message. This is called when a fact is added or deleted, sending an updated list of all facts for the user serialized as JSON.
This method is called when a fact is added or deleted. It fetches the updated list of facts for the user and creates a new FactsChanged object. This object is then converted into a JSON string and sent to the Pub/Sub topic through the sendToPubsub(String payload) method of the PubsubOutboundGateway. If there’s an error in the JSON serialization process, it will be logged.
This approach allows your application to send messages to Pub/Sub without being tightly coupled to Google Cloud–specific implementations, making your code more portable and easier to maintain.