Integrating Google Pub/Sub in a Spring Boot Application
Learn to integrate Google Pub/Sub with a Spring Boot application. Detailed guide includes creating a publisher, a subscriber, and a visual sequence diagram.
Google Cloud Pub/Sub is a messaging service for exchanging event data among applications and services. It provides reliable, many-to-many, asynchronous messaging between applications. In this article, we will cover the process of integrating Google Pub/Sub in a Spring Boot application using a real-world example. We will create a publisher that sends messages and a subscriber that receives those messages.
Setting Up Google Cloud Pub/Sub
Create a new project in the Google Cloud Console.
Enable the Pub/Sub API for your project.
Create a new topic.
Create a new subscription to that topic.
Download a private key file for your service account.
For detailed steps on how to achieve this, follow the official Google Cloud Pub/Sub documentation.
Setting Up Spring Boot Application
Create a new Spring Boot application. You can use Spring Initializr (
https://start.spring.io/
) to easily bootstrap your application. Make sure to add the “Spring Cloud GCP Messaging” and “Spring Web” dependencies.
In the
application.properties
file, add the following properties:
spring.cloud.gcp.project-id=your-gcp-project-id
spring.cloud.gcp.pubsub.credentials.location=file:path/to/your/service/account/key.json
Replace your-gcp-project-id
with your Google Cloud project ID, and path/to/your/service/account/key.json
with the path to your service account key file.
Creating Publisher
To create a publisher that publishes messages to a topic, we can use the PubSubTemplate
provided by the Spring Cloud GCP library. Here's an example of a REST controller that publishes messages:
import org.springframework.cloud.gcp.pubsub.core.PubSubTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class PublisherController {
private final PubSubTemplate pubSubTemplate;
public PublisherController(PubSubTemplate pubSubTemplate) {
this.pubSubTemplate = pubSubTemplate;
}
@PostMapping("/publish")
public String publishMessage(@RequestParam("message") String message) {
pubSubTemplate.publish("my-topic", message);
return "Message published successfully.";
}
}
In the above example, we inject PubSubTemplate
into our controller and use it to publish a message to the "my-topic" topic.
Creating Subscriber
To create a subscriber that receives messages from a subscription, we can use the @PubSubSubscription
annotation provided by the Spring Cloud GCP library. Here's an example of a service that receives messages:
import com.google.cloud.pubsub.v1.AckReplyConsumer;
import com.google.pubsub.v1.PubsubMessage;
import org.springframework.cloud.gcp.pubsub.support.GcpPubSubHeaders;
import org.springframework.cloud.gcp.pubsub.support.BasicAcknowledgeablePubsubMessage;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.cloud.gcp.pubsub.integration.AckMode;
import org.springframework.cloud.gcp.pubsub.integration.inbound.PubSubInboundChannelAdapter;
import org.springframework.cloud.gcp.pubsub.integration.inbound.PubSubMessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.context.annotation.Bean;
import org.springframework.integration.annotation.MessagingGateway;
import org.springframework.integration.annotation.Poller;
import org.springframework.stereotype.Service;
@Service
public class SubscriberService {
@ServiceActivator(inputChannel = "mySubscriptionInputChannel")
public void messageReceiver(String payload,
@Header(GcpPubSubHeaders.ORIGINAL_MESSAGE) BasicAcknowledgeablePubsubMessage message) {
System.out.println("Message received from Google Cloud Pub/Sub: " + payload);
// Acknowledge the message upon successful processing
message.ack();
}
}
In the above example, we define a method messageReceiver
that is triggered when a message arrives from the subscription. The @ServiceActivator(inputChannel = "mySubscriptionInputChannel")
annotation is used to specify the input channel from which this method will consume messages.
To configure the input channel, we need to create a PubSubInboundChannelAdapter
bean in the application configuration.
import org.springframework.cloud.gcp.pubsub.integration.inbound.PubSubInboundChannelAdapter;
import org.springframework.cloud.gcp.pubsub.support.converter.SimplePubSubMessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.messaging.MessageChannel;
@Configuration
public class PubSubConfig {
@Bean
public MessageChannel myInputChannel() {
return new DirectChannel();
}
@Bean
public PubSubInboundChannelAdapter messageChannelAdapter(
@Qualifier("myInputChannel") MessageChannel inputChannel,
PubSubTemplate pubSubTemplate) {
PubSubInboundChannelAdapter adapter = new PubSubInboundChannelAdapter(pubSubTemplate, "my-subscription");
adapter.setOutputChannel(inputChannel);
adapter.setPayloadConverter(new SimplePubSubMessageConverter());
return adapter;
}
}
In the above configuration, we create a PubSubInboundChannelAdapter
that listens to the "my-subscription" subscription and forwards the incoming messages to the "myInputChannel" channel.
This sequence diagram depicts the flow of messages in our example:
The Client makes a POST request to the
/publish
endpoint.The PublisherController publishes the message to Google Pub/Sub.
Google Pub/Sub delivers the message to the SubscriberService.
The SubscriberService acknowledges the message.
Conclusion
This article demonstrated how to integrate Google Cloud Pub/Sub in a Spring Boot application. We created a publisher that publishes messages to a topic and a subscriber that receives messages from a subscription. The Spring Cloud GCP library made the process relatively simple and straightforward.
🔗 Connect with me on LinkedIn!
I hope you found this article helpful! If you’re interested in learning more and staying up-to-date with my latest insights and articles, don’t hesitate to connect with me on LinkedIn.
Let’s grow our networks, engage in meaningful discussions, and share our experiences in the world of software development and beyond. Looking forward to connecting with you! 😊