<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Java Archives - Codersee blog- Kotlin on the backend</title>
	<atom:link href="https://blog.codersee.com/tag/java/feed/" rel="self" type="application/rss+xml" />
	<link></link>
	<description>Kotlin &#38; Backend Tutorials - Learn Through Practice.</description>
	<lastBuildDate>Wed, 16 Apr 2025 04:50:30 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	

<image>
	<url>https://blog.codersee.com/wp-content/uploads/2025/04/cropped-codersee_logo_circle_2-32x32.png</url>
	<title>Java Archives - Codersee blog- Kotlin on the backend</title>
	<link></link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Google Cloud Pub/Sub with Spring Boot and Java</title>
		<link>https://blog.codersee.com/google-cloud-pub-sub-with-spring-boot-and-java/</link>
					<comments>https://blog.codersee.com/google-cloud-pub-sub-with-spring-boot-and-java/#comments</comments>
		
		<dc:creator><![CDATA[Piotr]]></dc:creator>
		<pubDate>Thu, 08 Oct 2020 09:40:34 +0000</pubDate>
				<category><![CDATA[Spring]]></category>
		<category><![CDATA[Google Cloud]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Spring Boot]]></category>
		<guid isPermaLink="false">http://codersee.com/?p=1427</guid>

					<description><![CDATA[<p>In this step by step guide, we will learn how to set up Google Cloud Pub/Sub with Spring Boot Java application and Jackson JSON.</p>
<p>The post <a href="https://blog.codersee.com/google-cloud-pub-sub-with-spring-boot-and-java/">Google Cloud Pub/Sub with Spring Boot and Java</a> appeared first on <a href="https://blog.codersee.com">Codersee blog- Kotlin on the backend</a>.</p>
]]></description>
										<content:encoded><![CDATA[<h2 class="article-heading-introduction">1. Introduction</h2>
<p><a href="https://cloud.google.com/pubsub" target="_blank" rel="noopener noreferrer">Google Cloud Pub/Sub</a> might be a great tool to integrate decoupled systems hosted on <strong>GCP</strong> as well as elsewhere on the Internet. In this step-by-step guide, we will learn how to set up <strong>Google Cloud Pub/Sub with Spring Boot Java</strong> application.</p>
<p>Moreover, I will show you how to configure it for serialization and deserialization of <strong>POJOs</strong> using <strong>Jackson JSON</strong>.</p>
<h2 class="article-heading-introduction">2. Setup Google Cloud Project</h2>
<h3 class="article-heading-sub">2.1. Create Topic and Subscription</h3>
<p>As the first step, let&#8217;s go to the <a href="https://console.cloud.google.com/cloudpubsub" target="_blank" rel="noopener noreferrer">GCP console</a>, and let&#8217;s enable the <strong>Pub/Sub API</strong> for our future Spring Boot project by clicking the <em><strong>Enable</strong></em> button.</p>
<p>Alternatively, we can do the same with a <strong>gcloud CLI</strong> command:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="raw">gcloud services enable pubsub.googleapis.com
</pre>
<p>As the next step, let&#8217;s go to the <strong>Topics</strong> tab in the left sidebar and create a new topic named <em><strong>example</strong></em>:</p>
<p><img fetchpriority="high" decoding="async" class="post-image wp-image-1428 size-medium aligncenter" src="https://blog.codersee.com/wp-content/uploads/2020/10/1.png" alt="The image contains a screenshot from Google Cloud Platform console showing how to create a topic, which we will use to integrate pub/sub with Spring Boot Kotlin application later." width="503" height="333" /><br />
Or again, with a<strong> gcloud command</strong>:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="raw">gcloud pubsub topics create example</pre>
<p>Nextly, let&#8217;s go to the <strong>Subscriptions</strong> tab and click the <em><strong>create subscription</strong></em> button.</p>
<p>On this page, we can specify the subscription ID. Let&#8217;s call it an <em><strong>example-subscription</strong></em> and choose our previously created topic:</p>
<p><img decoding="async" class="post-image aligncenter wp-image-1429 size-medium" src="http://blog.codersee.com/wp-content/uploads/2020/10/2.png" alt="The image contains a screenshot from Google Cloud Platform console showing how to create a subscription for a Cloud Pub/Sub topic" width="585" height="262" srcset="https://blog.codersee.com/wp-content/uploads/2020/10/2.png 585w, https://blog.codersee.com/wp-content/uploads/2020/10/2-300x134.png 300w" sizes="(max-width: 585px) 100vw, 585px" /></p>
<p>Or, as usual, it can be done using <strong>CLI command</strong>:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="raw">gcloud pubsub subscriptions create example-subscription --topic=example</pre>
<p>If we would like to validate whether everything has been created, we can check it with these two commands:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="raw">gcloud pubsub subscriptions describe example-subscription
gcloud pubsub topics describe example
</pre>
<h3 class="article-heading-sub">2.2. Setup Service Account</h3>
<p>In this paragraph, we will learn how to create a service account, which will be used later in our <strong>Spring Boot</strong> project.</p>
<p>As the first step, let&#8217;s go to the <strong>GCP IAM &amp; Admin</strong> console and select the <a href="https://console.cloud.google.com/iam-admin/serviceaccounts" target="_blank" rel="noopener noreferrer">Service Accounts tab.</a> Then, let&#8217;s click the create service account button and specify the name as follows:<br />
<img decoding="async" class="post-image size-medium wp-image-1434 aligncenter" src="http://blog.codersee.com/wp-content/uploads/2020/10/3-2.png" alt="The image contains a screenshot from Google Cloud Platform console showing how to create a service account" width="679" height="464" srcset="https://blog.codersee.com/wp-content/uploads/2020/10/3-2.png 679w, https://blog.codersee.com/wp-content/uploads/2020/10/3-2-300x205.png 300w" sizes="(max-width: 679px) 100vw, 679px" /></p>
<p>&nbsp;</p>
<p>Nextly, we need to click continue, and on the next page, let&#8217;s add <em>Pub/Sub Admin</em> role:</p>
<p><img loading="lazy" decoding="async" class="post-image aligncenter wp-image-1431 size-medium" src="http://blog.codersee.com/wp-content/uploads/2020/10/4-300x183.png" alt="The image contains a screenshot from Google Cloud Platform console showing how to add the Pub/Sub admin role to the service account" width="300" height="183" srcset="https://blog.codersee.com/wp-content/uploads/2020/10/4-300x183.png 300w, https://blog.codersee.com/wp-content/uploads/2020/10/4.png 718w" sizes="auto, (max-width: 300px) 100vw, 300px" /></p>
<p>After the role has been added, we need to click next and finally click done. We will be redirected to the page showing all service accounts in our project. Let&#8217;s click the three dots near to the recently created Pub/Sub service account and click<em> <strong>Create key</strong></em>:</p>
<p><img loading="lazy" decoding="async" class="post-image alignnone wp-image-1432" src="http://blog.codersee.com/wp-content/uploads/2020/10/5.png" alt="The image contains a screenshot from Google Cloud Platform console showing how to create a key" width="1055" height="152" srcset="https://blog.codersee.com/wp-content/uploads/2020/10/5.png 1338w, https://blog.codersee.com/wp-content/uploads/2020/10/5-300x43.png 300w, https://blog.codersee.com/wp-content/uploads/2020/10/5-1024x148.png 1024w, https://blog.codersee.com/wp-content/uploads/2020/10/5-768x111.png 768w" sizes="auto, (max-width: 1055px) 100vw, 1055px" /><br />
As the key type, let&#8217;s select the <strong>JSON</strong>:</p>
<p><img loading="lazy" decoding="async" class="post-image size-medium wp-image-1433 aligncenter" src="http://blog.codersee.com/wp-content/uploads/2020/10/6.png" alt="The image contains a screenshot from Google Cloud Platform console showing how to choose the JSON key" width="565" height="360" srcset="https://blog.codersee.com/wp-content/uploads/2020/10/6.png 565w, https://blog.codersee.com/wp-content/uploads/2020/10/6-300x191.png 300w" sizes="auto, (max-width: 565px) 100vw, 565px" /></p>
<p>&nbsp;</p>
<p>As the last step, please download the file and put it inside the <strong>resources</strong> directory of the <strong>Spring Boot project</strong>.</p>
<h2 class="article-heading-introduction">3. Imports</h2>
<p>If all the Pub/Sub steps above have been completed, we can switch to the<strong> Spring Boot project</strong>. Firstly, let&#8217;s import two dependencies we will need for our project to work:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="groovy">  
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.cloud:spring-cloud-gcp-starter-pubsub'
</pre>
<h2 class="article-heading-introduction">4. Configure Application Properties</h2>
<p>As the next step, let&#8217;s define the <strong>application.yaml</strong> file as follows:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="yaml"> 
pubsub-example:
  subscription:
    name: ${EXAMPLE_PUBSUB_SUBSCRIPTION}
  topic:
    name: ${EXAMPLE_PUBSUB_TOPIC}

spring:
  cloud:
    gcp:
      credentials:
        location: classpath:credentials.json
</pre>
<p>Please notice, the name of the <strong>JSON</strong> should match the name of <strong>the file that we&#8217;ve put inside the resources folder</strong>. Also, the environment variables describing subscription and topic should be set to the correct values, for example:</p>
<ul>
<li><em>EXAMPLE_PUBSUB_SUBSCRIPTION</em> -&gt; projects/[PROJECT-ID]/subscriptions/example-subscription</li>
<li><em>EXAMPLE_PUBSUB_TOPIC</em> -&gt; projects/[PROJECT-ID]/topics/example</li>
</ul>
<h2 class="article-heading-introduction">6. Create a POJO Class</h2>
<p>Our next step is to create a simple <strong>POJO</strong> class, which will be used for the serialization and deserialization of the messages sent through the <strong>Pub/Sub</strong>:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="java">  
public class MessageEntity {

    private final LocalDateTime timestamp;
    private final String message;
    
    //constructor, getters, setters
}
</pre>
<p>As you can see, it is a simple class containing the timestamp and the value of the message.</p>
<h2 class="article-heading-introduction">7. Set Up The Consumer</h2>
<p>Let&#8217;s start the work on the consumer part by creating the <strong>PubSubConsumer</strong> interface:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="java">  
public interface PubSubConsumer {

    String subscription();

    Class payloadType();

    Consumer&lt;ConvertedBasicAcknowledgeablePubsubMessage&gt; messageConsumer();
}
</pre>
<p>As you can see, this interface consists of three methods definitions:</p>
<ul>
<li><em>subscription</em> -&gt; returns the name of the subscription</li>
<li><em>payloadTyme</em> -&gt; returns the Class object representing the target type of the payload</li>
<li><em>messageConsumer</em> -&gt; returns the callback method triggered when new messages arrive</li>
</ul>
<p>Technically, we don&#8217;t need this interface, but with this approach, we will be able to add easily more consumers in the future.</p>
<p>Secondly, let&#8217;s create the <strong>ExampleCosumer</strong> class implementing the interface:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="java">  
@Component
public class ExampleConsumer implements PubSubConsumer {

    private static final Logger log = LoggerFactory.getLogger(ExampleConsumer.class);
    private final String subscriptionName;

    public ExampleConsumer(
        @Value("${pubsub-example.subscription.name}") String subscriptionName
    ) {
        this.subscriptionName = subscriptionName;
    }
}
</pre>
<p>As you might have noticed, our class contains two fields: a <em>logger</em> and a <em>subscriptionName</em> which will be bound with the value from our <strong>properties.yaml</strong> file.</p>
<p>Please remember, that our class implements <strong>PubSubConsumer, </strong>so as the next step we need to provide the definition for each method:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="java">  
@Override
public String subscription() {
    return subscriptionName;
}

@Override
public Class payloadType() {
    return MessageEntity.class;
}

@Override
public Consumer&lt;ConvertedBasicAcknowledgeablePubsubMessage&gt; messageConsumer() {
    return this::consume;
}
</pre>
<p>To keep our code more readable, let&#8217;s implement our consumer method as a separate function:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="java">  
private void consume(ConvertedBasicAcknowledgeablePubsubMessage message) {
    MessageEntity received = message.getPayload();

    log.info(
        "Received entity: [timestamp= {}, message= {}]",
        received.getTimestamp(),
        received.getMessage()
    );

    message.ack();
}
</pre>
<p>To put it simply, this method extracts the payload from the <strong>ConvertedBasicAcknowledgeablePubsubMessage</strong> object and logs the timestamp and the message at the INFO level. In the end, it asynchronously acknowledges the message.</p>
<p>As the next step, let&#8217;s create <strong>ExampleSubscriberConfig</strong> class and put the configuration for our subscriber there:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="java">  
@Configuration
public class ExampleSubscriberConfig {

    private static final Logger log = LoggerFactory.getLogger(ExampleSubscriberConfig.class);

    private final PubSubTemplate pubSubTemplate;
    private final PubSubConsumer exampleConsumer;

   //constructor
}
</pre>
<p>As you might have noticed, besides the logger and the <em>exampleConsumer</em>, we are injecting <em>pubsubTemplate</em>, which will be used for publishing to topics and consuming messages.</p>
<p>Let&#8217;s implement the method responsible for subscription:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="java">  
@EventListener(ApplicationReadyEvent.class)
public void subscribe() {
    log.info("Subscribing to {}", exampleConsumer.subscription());

    pubSubTemplate.subscribeAndConvert(
        exampleConsumer.subscription(),
        exampleConsumer.messageConsumer(),
        exampleConsumer.payloadType()
    );
}
</pre>
<p>The annotation  <em><strong>EventListener</strong></em> used with <strong>ApplicationReadyEvent</strong> indicates, that the method will be called when the application is ready to receive requests.</p>
<p>As the last step, we need to provide the bean definition for a converter using <strong>Jackson JSON</strong>:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="java">  
@Configuration
public class PubSubConfig {

    @Bean
    public JacksonPubSubMessageConverter jacksonPubSubMessageConverter(ObjectMapper objectMapper) {
        return new JacksonPubSubMessageConverter(objectMapper);
    }
}
</pre>
<p>With that being done, we are ready to receive the messages.</p>
<h2 class="article-heading-introduction">8. Set Up The Publisher</h2>
<p>Besides receiving the messages, it would be good to have the possibility to publish some. Let&#8217;s start the work on the publisher part by creating the <strong>ExamplePublisher</strong> class:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="java">  
@Component
public class ExamplePublisher {

    private final String topic;
    private final PubSubTemplate pubSubTemplate;

    public ExamplePublisher(
        @Value("${pubsub-example.topic.name}") String topic,
        PubSubTemplate pubSubTemplate) {
        this.topic = topic;
        this.pubSubTemplate = pubSubTemplate;
    }
}
</pre>
<p>As we can see, we need to inject the <strong>PubSubTemplate</strong> bean and the topic, which will be set to the value from the application properties.</p>
<p>Let&#8217;s add a publish method then. It will take the <strong>MessageEntity</strong> as the argument:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="java">  
public void publish(MessageEntity payload) {
    pubSubTemplate.publish(topic, payload);
}
</pre>
<p>As you might have noticed, this method uses the <em>publish</em> method to push the object to the specified Pub/Sub topic.</p>
<h2 class="article-heading-introduction">9. Create Example Controller</h2>
<p>And finally, we can implement the <strong>TestController</strong> class:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="java">  
@RestController
@RequestMapping("/api")
public class TestController {

    private final ExamplePublisher publisher;

    public TestController(ExamplePublisher publisher) {
        this.publisher = publisher;
    }

    @PostMapping("/topic")
    public void publish(@RequestBody String message) {
        MessageEntity entity = new MessageEntity(LocalDateTime.now(), message);
        publisher.publish(entity);
    }
}
</pre>
<p>It&#8217;s just a simple REST controller, which will be responding to the POST<em> /api/topic</em> calls and forwarding the message to the publisher.</p>
<h2 class="article-heading-introduction">10. Testing Using Curl</h2>
<p>Lastly, there is nothing else to do than just test our application with the following command:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="raw">  
curl -d 'Some message' localhost:8080/api/topic
</pre>
<p>After it executes, we should see a new entry in our application logs (and each time we call the endpoint as well).</p>
<h2 class="article-heading-main">9. GCP Pub/Sub With Spring Boot Conclusion</h2>
<p>And I believe, that&#8217;s all for today. In this step-by-step tutorial, we&#8217;ve learned how to publish and receive messages through the<strong> Google Cloud Pub/Sub</strong> using <strong>the Spring Boot Java </strong>application.</p>
<p>I hope that you&#8217;ve really enjoyed this guide. I would be forever grateful if you would like to share some feedback with me. Would you like to see more Java tutorials as well? Please, let me know about it using our <a href="https://www.facebook.com/codersee/" target="_blank" rel="noopener noreferrer"><strong>page</strong></a>, <a href="https://www.facebook.com/groups/622361565094117" target="_blank" rel="noopener noreferrer"><strong>group</strong></a>, or <strong><a href="https://codersee.com/contact/" target="_blank" rel="noopener noreferrer">contact</a> </strong>form.</p>
<p>For the source code of the project, please visit our project on <a href="https://github.com/codersee-blog/java-spring-boot-pubsub" target="_blank" rel="noopener noreferrer"><strong>GitHub</strong></a>.</p>
<p>The post <a href="https://blog.codersee.com/google-cloud-pub-sub-with-spring-boot-and-java/">Google Cloud Pub/Sub with Spring Boot and Java</a> appeared first on <a href="https://blog.codersee.com">Codersee blog- Kotlin on the backend</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.codersee.com/google-cloud-pub-sub-with-spring-boot-and-java/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
			</item>
	</channel>
</rss>

<!--
Performance optimized by W3 Total Cache. Learn more: https://www.boldgrid.com/w3-total-cache/?utm_source=w3tc&utm_medium=footer_comment&utm_campaign=free_plugin

Page Caching using Disk: Enhanced 

Served from: blog.codersee.com @ 2026-04-19 03:09:41 by W3 Total Cache
-->