DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Distributed Tracing System (Spring Cloud Sleuth + OpenZipkin)
  • How to Create Microservices Using Spring
  • Spring Cloud Stream: A Brief Guide
  • Full-Duplex Scalable Client-Server Communication with WebSockets and Spring Boot (Part I)

Trending

  • Proactive Security in Distributed Systems: A Developer’s Approach
  • Prioritizing Cloud Security Risks: A Developer's Guide to Tackling Security Debt
  • Rust, WASM, and Edge: Next-Level Performance
  • Infrastructure as Code (IaC) Beyond the Basics
  1. DZone
  2. Coding
  3. Frameworks
  4. Spring Boot: Messaging With RabbitMQ Pub/Sub in PCF

Spring Boot: Messaging With RabbitMQ Pub/Sub in PCF

Want to learn more about using the RabbitMQ messenger? Check out this tutorial on how to create a messaging model with Spring Boot.

By 
Prasanth Mohan user avatar
Prasanth Mohan
·
Updated Sep. 25, 18 · Tutorial
Likes (5)
Comment
Save
Tweet
Share
20.4K Views

Join the DZone community and get the full member experience.

Join For Free

In my previous article, I demonstrated how to create a simple RabbitMQ message producer and consumer. In this article, I would like to demonstrate how to create a simple RabbitMQ pub/sub messaging model using the Spring Boot starter packs and what it takes to deploy the application in PCF. 

In the example below, I will create a simple message producer that will send a message to an exchange, which, in turn, will route the message to the appropriate queue based on the routing key. Once the message is sent to the appropriate queue, we will consume the same and print it in the console. For the sake of simplicity, I'm using the direct exchange. If you want to experiment with other types of exchanges, like Topic, Default or Fanout, you will have to create and inject the beans accordingly.

build.gradle

buildscript {   
  ext {      
    springBootVersion = '2.0.4.RELEASE'   
  }   
  repositories {      
    mavenCentral()   
  }   
  dependencies {      
    classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")   
  }
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'

group = 'com.pras'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8

repositories {   
  mavenCentral()
}

dependencies {   
  compile('org.springframework.boot:spring-boot-starter-amqp')   
  compile('org.springframework.boot:spring-boot-starter-cloud-connectors')   
  compile('org.springframework.boot:spring-boot-starter-web')   
  testCompile('org.springframework.boot:spring-boot-starter-test')
}


The spring-boot-starter-cloud-connectors  will add the following dependencies to your project.

  • spring-cloud-cloudfoundry-connector

  • spring-cloud-connectors-core

  • spring-cloud-heroku-connector

  • spring-cloud-spring-service-connector

  • spring-cloud-localconfig-connector

In your local environment, Spring Boot will auto-configure the ConnectionFactory bean with the default host URL (localhost) and default host port (5672) of the local RabbitMQ instance and inject the same to the Spring container. But, when it comes to the cloud environment, we need to auto-configure the ConnectionFactory bean with the bounded RabbitMQ instance's URL and port and inject the same. And, this is exactly what the Spring Cloud connectors will do.

MessageProducer.java

package com.pras.rabbitmqtopic.messaging;

import org.springframework.amqp.core.Exchange;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

@Component
public class MessageProducer {    

  private final RabbitTemplate rabbitTemplate;    

  public MessageProducer(RabbitTemplate rabbitTemplate){       
    this.rabbitTemplate = rabbitTemplate;    
  }    

  public void sendFirstMessage(){        
    this.rabbitTemplate.convertAndSend("directExchange", "first","Welcome"); 
  }    

  public void sendSecondMessage(){        
    this.rabbitTemplate.convertAndSend("directExchange", "second","Welcome Again");    
  }
}


MessageConsumer.java

package com.pras.rabbitmqtopic.messaging;

import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@Component
public class MessageConsumer {    

  @RabbitListener(queues = "First_Queue")    
  public void consumeFirstQueueMessage(String message){        
    System.out.println("First Queue Message *****************" + message);    
  }    

  @RabbitListener(queues = "Second_Queue")    
  public void consumeSecondQueueMessage(String message){        
    System.out.println("Second Queue Message *****************" + message);    
  }
}


BasicConfiguration.java

package com.pras.rabbitmqtopic.messaging;

import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class BasicConfiguration {    

  @Bean    
  public Queue firstQueue(){        
    return new Queue("First_Queue");    
  }   

  @Bean    
  public Queue secondQueue(){        
    return new Queue("Second_Queue");    
  }    

  @Bean    
  public Exchange sampleExchange(){        
    return new DirectExchange("directExchange");    
  }    

  @Bean    
  public Binding firstBinding(Queue firstQueue, DirectExchange directExchange){
    return BindingBuilder.bind(firstQueue).to(directExchange).with("first"); 
  }    

  @Bean    
  public Binding secondBinding(Queue secondQueue, DirectExchange directExchange){ 
    return BindingBuilder.bind(secondQueue).to(directExchange).with("second");    
  }
}


For testing purposes, I also exposed an API to drop the message into the queue. 

BaseController.java

package com.pras.rabbitmqtopic.controller;

import com.pras.rabbitmqtopic.messaging.MessageProducer;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class BaseController {    

  private final MessageProducer messageProducer;    

  public BaseController(MessageProducer messageProducer){       
    this.messageProducer = messageProducer;    
  }   

  @GetMapping("/testRabbitTopic")    
  public void testRabbitTopic(){       
    messageProducer.sendFirstMessage();       
    messageProducer.sendSecondMessage();    
  }
}


Note: You could also drop a message directly using the RabbitMQ admin console for testing purposes.

Once the above code is in place, we can compile the code and build the jar, which we will be pushing into PCF (by default, the jar will get created inside build/libs).

./gradlew clean build -x test


Once you have logged into your PCF org/space, we can push the application into PCF using the following command. Since the app is not bound to the RabbitMQ instance yet, the application will fail on startup. That's why we are pushing the application with  --no-start.

cf push sampleapp -p build/libs/spring-boot-pcf-rabbitmq-message-producer-0.0.1-SNAPSHOT.jar --no-start


Create a new instance of rabbit-mq, which will be bound to the sample app later.

cf create-service p-rabbit-mq standard my-rabbitmq


Next, we need to bind our application to the newly created rabbit-mq instance.

cf bind-service sampleapp my-rabbitmq


After this, you will restage the application for the change to take effect.

cf restage sampleapp


If you want to dockerize your app and deploy it in PCF, then you should set the SPRING_PROFILES_ACTIVE to cloud. If you don't set the env value, then you will get a connection refused error in your logs when you try to start the application.

cf set-env sampleapp SPRING_PROFILES_ACTIVE cloud


Testing

When you invoke the endpoint /testRabbitTopic, you will see the below logs in your container console.

Image title

Spring Framework Spring Boot application Spring Cloud

Opinions expressed by DZone contributors are their own.

Related

  • Distributed Tracing System (Spring Cloud Sleuth + OpenZipkin)
  • How to Create Microservices Using Spring
  • Spring Cloud Stream: A Brief Guide
  • Full-Duplex Scalable Client-Server Communication with WebSockets and Spring Boot (Part I)

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!