Spring Boot RabbitMQ Message Publishing Example

By |2019-06-05T22:59:06+05:30June 5th, 2019|Spring Boot|

In this tutorial, we are going to see an example for Spring Boot RabbitMQ Message Publishing.

Spring Boot RabbitMQ Message Publishing:

As part of this example, we will be sending JSON messages to RabbitMQ queue.

Prerequisites:

Technologies:

  • Spring Boot 2.1.4 RELEASE
  • Spring Boot Started AMQP
  • RabbitMQ 3.7.15
  • Lombok
  • Java8
  • Maven

1 Project Structure:

Spring Boot Data Rest Example-min

2 Project Dependencies:

pom.xml
<dependencies>
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-amqp</artifactId>
  </dependency>
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
  </dependency>
  <dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <optional>true</optional>
  </dependency>
</dependencies>

3. RabbitMQ properties:

Configuring RabbitMQ server URL, port, username and password details in application.properties file.

application.properties
spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest

4. Item Model:

Creating Item model class, representing the Item JSON message. Which will be sent to RabbitMQ queue.

Item.java
package com.onlinetutorialspoint.model;

import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
import lombok.Data;
import lombok.NoArgsConstructor;

@JsonIdentityInfo(generator = ObjectIdGenerators.IntSequenceGenerator.class,property = "@id",scope = Item.class)
@Data
@NoArgsConstructor
public class Item {
    private String itemName;
    private String category;
    private String description;
}

5. RabbitMQ configurations:

Creating a RabbitMQ config class with all necessary beans to get RabbitMq queue, exchange, and routing key.

Note: I have created a queue, exchange, and routing key from RabbitMQ management console and given the same queue, exchange and routing key names while creating appropriate beans.
RabbitMQConfig.java
package com.onlinetutorialspoint.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RabbitMQConfig {

    private String QUEUE="items-queue";

    private String EXCHANGE="otp-exchange";

    private String ROUTING_KEY="items";
    @Bean
    Queue queue() {
        return new Queue(QUEUE, true);
    }
    @Bean
    DirectExchange exchange() {
        return new DirectExchange(EXCHANGE);
    }

    @Bean
    Binding binding(Queue queue, DirectExchange exchange) {
        return BindingBuilder.bind(queue).to(exchange).with(ROUTING_KEY);
    }
    @Bean
    public MessageConverter jsonMessageConverter() {
        return new Jackson2JsonMessageConverter();
    }

    @Bean
    public AmqpTemplate amqpTemplate(ConnectionFactory connectionFactory) {
        final RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        rabbitTemplate.setMessageConverter(jsonMessageConverter());
        return rabbitTemplate;
    }
}

AmqpTemplate specifies a basic set of AMQP operations; it provides synchronous send and receives messages.

If you are going to send/receive messages in the form of POJOs, it should be expected to delegate to an instance of MessageConverter to perform the conversion from AMQP byte[] payload type.

6. RabbitMQ Service:

Creating RabbitMQService class which is responsible for sending messages on RabbitMQ queue using AmqpTemplate.

RabbitMqService.java
package com.onlinetutorialspoint.service;

import com.onlinetutorialspoint.model.Item;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class RabbitMqService {
    @Autowired
    private AmqpTemplate amqpTemplate;

    private String EXCHANGE="otp-exchange";

    private String ROUTING_KEY="items";

    public void sendMessage(Item item) {
        amqpTemplate.convertAndSend(EXCHANGE, ROUTING_KEY, item);
    }
}

The convertAndSend() methods allow you to send POJO objects.

7. Rest Controller:

Creating RabbitMqController class having one post method to post Item message on RabbitMQ.

RabbitMqController.java
package com.onlinetutorialspoint.controller;

import com.onlinetutorialspoint.model.Item;
import com.onlinetutorialspoint.service.RabbitMqService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class RabbitMqController {
    @Autowired
    RabbitMqService rabbitMqService;

    @PostMapping("/items")
    public ResponseEntity<String> postMessage(@RequestBody Item item){
        rabbitMqService.sendMessage(item);
        return new ResponseEntity<String>("Item pushed to RabbitMQ",HttpStatus.CREATED);
    }
}

8. Main-Class:

SpringBootRabbitMqProducerApplication.java
package com.onlinetutorialspoint;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringBootRabbitMqProducerApplication {

  public static void main(String[] args) {
    SpringApplication.run(SpringBootRabbitMqProducerApplication.class, args);
  }

}

9. Run It:

Terminal
  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.4.RELEASE)

2019-06-05 21:10:05.250  INFO 8388 --- [           main] .o.SpringBootRabbitMqProducerApplication : Starting SpringBootRabbitMqProducerApplication on DESKTOP-RN4SMHT with PID 8388 (D:\work\Spring-Boot-RabbitMQ-Producer\target\classes started by Lenovo in D:\work\Spring-Boot-RabbitMQ-Producer)
2019-06-05 21:10:05.250  INFO 8388 --- [           main] .o.SpringBootRabbitMqProducerApplication : No active profile set, falling back to default profiles: default
2019-06-05 21:10:09.172  INFO 8388 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
.....
.....

Accessing the application through localhost:8080/items from the postman and sending a POST request.

Spring Boot RabbitMQ Message Publishing Example2-min

10. Verify in RabbitMQ:

Login to RabbitMQ management console http://localhost:15672

Goto Queues click on the queue which you configured and expand the Messages; there you can see the messages like below.

Spring Boot RabbitMQ Message Publishing Example3-min

References:

Download Source from GIT:

Happy Learning 🙂

About the Author:

Hi Folks, you have reach this so far, that shows you like what you are learning. Then why don't you support us to improve for bettor tutorials by leaving your valuable comments and why not you keep in touch with us for latest updates on your favorite blog @ facebook , twitter , Or Google+ ,

Leave A Comment