Spring Cloud GCP for Pub/Sub

Reading Time: 3 minutes

This is the first blog in the Spring Cloud GCP- Cloud Pub/Sub. In this blog, we will create an application to receive messages that are sent by the sender application. 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 this blog, we have to download 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.

Triggering messages

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 a 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: The 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 blogs is referred from Spring and GCP documentation.

Conclusion

In this blog, we tried to understand how to send and receive messages using Google Cloud Pub/Sub in the 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 

He is a Software Consultant at Knoldus Inc. He has done B.Tech from Dr. APJ Kalam Technical University Uttar-Pradesh. He is passionate about his work and having the knowledge of various programming languages like Java, C++, Python. But he is passionate about Java development and curious to learn Java Technologies. He is always impatient and enthusiastic to learn new things. He is good skills of Critical thinking and problem solving and always enjoy to help others. He likes to play outdoor games like Football, Volleyball, Hockey and Kabaddi. Apart from the technology he likes to read scriptures originating in ancient India like Veda,Upanishad,Geeta etc.

Leave a Reply