Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Spring Boot: Messaging With RabbitMQ Pub/Sub in PCF

DZone 's Guide to

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.

· Java Zone ·
Free Resource

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

Topics:
spring-boot ,pcf ,rabbitmq

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}