Spring Cloud GCP- Cloud Pub/Sub Receiving Messages

black samsung tablet display google browser on screen
Reading Time: 3 minutes

This is the second blog in the series Spring Cloud GCP- Cloud Pub/Sub. If you have not gone through the first part please navigate to Spring Cloud GCP- Cloud Pub/Sub Sending Messages.

In this blog, we will create an application to receive messages that are sent by the sender application that we created in the last blog. We will use Google Cloud Pub/Sub as the underlying messaging system. To integrate Google Cloud Pub/Sub with our application we will be using Spring.

As part of the last blog, we have downloaded the basic receiver application and its dependencies to GCP.

Now, we will replicate the same configurations and download a project from Spring Initializr to our local machine to make the necessary changes for it to be able to receive the messages. Then, we will copy the code into our receiver app present in GCP and run it.

Creating the receiver app

Firstly, download the initial app from Spring Initializr. Please refer to the following image for reference:

Spring Initializr Configuration

After the project file is downloaded on your local machine, open it in the IDE of your choice.

Now, navigate to your main application class in your IDE.

The first thing we need to do is to create a message channel where we will receive the incoming messages. Add the following piece of code:

import org.springframework.context.annotation.Bean;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.messaging.MessageChannel;

@SpringBootApplication
public class SpringCloudMessagingReceiverApplication {

  ...

  @Bean
  public MessageChannel pubsubInputChannel() {
    return new DirectChannel();
  }
}

Next, we need the inbound channel adapter to receive messages from Cloud Pub/Sub and send them to pubsubInputChannel. Add the following piece of code to the class:

import com.google.cloud.spring.pubsub.core.PubSubTemplate;
import com.google.cloud.spring.pubsub.integration.inbound.PubSubInboundChannelAdapter;

import org.springframework.beans.factory.annotation.Qualifier;

@SpringBootApplication
public class SpringCloudMessagingReceiverApplication {

  ...

  @Bean
  public PubSubInboundChannelAdapter messageChannelAdapter(
      @Qualifier("pubsubInputChannel") MessageChannel inputChannel,
      PubSubTemplate pubSubTemplate) {
    PubSubInboundChannelAdapter adapter =
        new PubSubInboundChannelAdapter(pubSubTemplate, "my-first-topic-sub");
    adapter.setOutputChannel(inputChannel);

    return adapter;
  }
}

This adapter binds itself to the pubsubInputChannel and listens to new messages from my-first-topic-sub subscription.

In the previous step, we have already created a channel where incoming messages are sent. Now, Let’s process them with a @ServiceActivator that is triggered when new messages arrive at pubsubInputChannel. Then we will use logger to print out the message from the payload.

Please add the following piece of code to the class:

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.integration.annotation.ServiceActivator;

@SpringBootApplication
public class SpringCloudMessagingReceiverApplication {

  ...

  private static final Log LOGGER = LogFactory.getLog(SpringCloudMessagingReceiverApplication.class);

  @ServiceActivator(inputChannel = "pubsubInputChannel")
  public void messageReceiver(String payload) {
    LOGGER.info("Message arrived! Payload: " + payload);
  }
}

Finally, we are done with the app finally it’s time to run and test it.

Copy this whole code over to the GCP environment’s corresponding receiver app.

NOTE: GCP environment has the name DemoApplication for the main class please rename the class if needed.

Then run the app using GCP Cloud Shell:

./mvnw spring-boot:run -Dspring-boot.run.jvmArguments="-Dserver.port=8081"

Now, the messages you send from the sender app will be received on the receiver app. Let us verify the same:

Open a new Cloud Shell tab by clicking on the small plus button right beside the current tab. Send an HTTP POST request to the sender app:

curl --data "message=First Message" localhost:8080/postMessage

Then, you should be able to see the messages getting logged in the other tab where the receiver app is running.

INFO: Message arrived! Payload: First Message

If not, please recheck both the codes and if both applications are running properly on the GCP cloud shell and then try again.

References

All the content on both the blogs is referred from Spring and GCP documentations.

Conclusion

In these two blogs, we tried to understand how to send and receive messages using Google Cloud Pub/Sub in Spring project. This is just a basic sender-receiver system for learning purposes you may try to implement Cloud Pub/Sub messaging in your existing Spring-Kafka projects.

For more such awesome Tech Blogs on GCP services and various other technologies please follow Knoldus Blogs.

Written by 

Agnibhas Chattopadhyay is a Software Consultant at Knoldus Inc. He is very passionate about Technology and Basketball. Experienced in languages like C, C++, Java, Python and frameworks like Spring/Springboot, Apache Kafka and CI/CD tools like Jenkins, Docker. He loves sharing knowledge by writing easy to understand tech blogs.

Discover more from Knoldus Blogs

Subscribe now to keep reading and get access to the full archive.

Continue reading