Learn RabbitMQ with SpringBoot

news/2024/11/7 9:39:11/

文章目录

  • What is RabbitMQ?
  • RabbitMQ Core concept
  • RabbitMQ Architecture
  • Install and setup RabbitMQ using Docker
  • Explore RabbitMQ using management UI
  • Create and setup Springboot3 project in intellij
  • Springboot and RabbitMQ Basic Message
    • Connection between Springboot and RabbitMQ
    • Create core component
    • Create RabbitMQProducer
    • Create REST API to send message
    • create RabbitMQConsumer
  • Springboot and RabbitMQ Json Message
    • Create Json object
    • add config
    • Produce json message
    • Create API to send json object
    • Consum json message

What is RabbitMQ?

RabbitMQ Core concept

RabbitMQ Architecture

Install and setup RabbitMQ using Docker

# notice: select 3.11.15-management, it will have web management web page
docker pull rabbitmq:3.11.15-management
docker run --rm  -it -p 15672:15672 -p 5672:5672 rabbitmq:3.11.0

Explore RabbitMQ using management UI

when we first login, username is guest and password is guest. Then we do some common operations in the dashboard.

  • create exchange
    在这里插入图片描述
  • create queue
    在这里插入图片描述
  • binding exchange with queue using routing key
    在这里插入图片描述

在这里插入图片描述
After finish all the operations, we can test whether it is work here. So publish a message to exchange, if we can get message in queue, we can think it works.
在这里插入图片描述

在这里插入图片描述

Create and setup Springboot3 project in intellij

First, using spring initializr to quick create and bootstrap spring boot project.
在这里插入图片描述
Second, using intellij open the project.
在这里插入图片描述

Springboot and RabbitMQ Basic Message

Connection between Springboot and RabbitMQ

Springboot autoconfiguration for spring AMQP(RabbitMQ). We get a connection to our RabbitMQ broker on port 5672 using the default username and password of "guest".

Define these proprtties in a application.properties.

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

Create core component

  • setup queue name, exchange name and routing key name in application.properties.
spring.rabbitmq.queue_name=fan_queue
spring.rabbitmq.exchange_name=fan_exchange
spring.rabbitmq.routing_key=fan_routing_key
  • write the java code to create queue, exchange and binding.
// file path: com/fan/springbootrabbitmq/config
package com.fan.springbootrabbitmq.config;import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;@Configuration
public class RabbitMQConfig {@Value("${spring.rabbitmq.queue_name}")private String queueName;@Value("${spring.rabbitmq.exchange_name}")private String exchangeName;@Value("${spring.rabbitmq.routing_key}")private String routingKey;// spring bean for rabbitmq queue@Beanpublic Queue queue() {return new Queue(queueName);}// spring bean for rabbitmq exchange@Beanpublic TopicExchange exchange() {return new TopicExchange(exchangeName);}// binding between queue and exchange using routing key@Beanpublic Binding binding() {return BindingBuilder.bind(queue()).to(exchange()).with(routingKey);}
}
  • rerun the project and check whether there are error, if no error, it works.

Create RabbitMQProducer

// file path:  com/fan/springbootrabbitmq/publisher/RabbitMQProducer.java
package com.fan.springbootrabbitmq.publisher;import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;@Service
public class RabbitMQProducer {@Value("${spring.rabbitmq.exchange_name}")private String exchangeName;@Value("${spring.rabbitmq.routing_key}")private String routingKey;// use RabbitTemplate to send the messages. it auto config for us, we just need to inject and use it.private final RabbitTemplate rabbitTemplate;private static final Logger LOGGER = LoggerFactory.getLogger(RabbitMQProducer.class);public RabbitMQProducer(RabbitTemplate rabbitTemplate) {this.rabbitTemplate = rabbitTemplate;}public void sendMessage(String message) {LOGGER.info(String.format("Message sent => %s", message));rabbitTemplate.convertAndSend(exchangeName, routingKey, message);}
}

Create REST API to send message

// file path: com/fan/springbootrabbitmq/controller/RabbitMQController.java
package com.fan.springbootrabbitmq.controller;import com.fan.springbootrabbitmq.publisher.RabbitMQProducer;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;@RestController
@RequestMapping("/api/v1")
public class RabbitMQController {private RabbitMQProducer producer;public RabbitMQController(RabbitMQProducer producer) {this.producer = producer;}@GetMapping("/publish")public ResponseEntity<String> publish(@RequestParam("message") String message) {producer.sendMessage(message);return ResponseEntity.ok("Message sent to rabbitmq...");}
}

how to test?

  • send api request to send message to rabbitmq: http://localhost:8080/api/v1/publish?message=xxx
  • check in the dashboard: http://localhost:15672/

create RabbitMQConsumer

// file path: com/fan/springbootrabbitmq/publisher/RabbitMQConsumer.java
package com.fan.springbootrabbitmq.publisher;import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;@Service
public class RabbitMQConsumer {private static final Logger LOGGER = LoggerFactory.getLogger(RabbitMQProducer.class);@RabbitListener(queues = "${spring.rabbitmq.queue_name}")public void consum(String message) {LOGGER.info(String.format("Message received => %s", message));}}

after finish this part, rerun the project and send a request for sending message to rabbitmq, and then you can see the result in peoject like this:

[ntContainer#0-1] c.f.s.publisher.RabbitMQProducer         : Message sent => hello1
[ntContainer#0-1] c.f.s.publisher.RabbitMQProducer         : Message received => hello1

Springboot and RabbitMQ Json Message

Create Json object

// file path: com/fan/springbootrabbitmq/dto/User.java
package com.fan.springbootrabbitmq.dto;import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {private Long id;private String firstName;private String lastName;
}

add config

// file path: com/fan/springbootrabbitmq/config/RabbitMQConfig.java// add this attributes to RabbitMQConfig class@Value("${spring.rabbitmq.json.queue_name}")private String queueJsonName;@Value("${spring.rabbitmq.json.routing_key}")private String routingJsonKey;// add this methods to RabbitMQConfig class@Beanpublic Queue jsonQueue() {return new Queue(queueJsonName);}@Beanpublic MessageConverter converter(){return new Jackson2JsonMessageConverter();}@Beanpublic AmqpTemplate amqpTemplate(ConnectionFactory connectionFactory){RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);rabbitTemplate.setMessageConverter(converter());return rabbitTemplate;}@Beanpublic Binding jsonBinding() {return BindingBuilder.bind(jsonQueue()).to(exchange()).with(routingJsonKey);}

Produce json message

// file path: com/fan/springbootrabbitmq/publisher/RabbitMQJsonProducer.java
package com.fan.springbootrabbitmq.publisher;import com.fan.springbootrabbitmq.dto.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;@Service
public class RabbitMQJsonProducer {@Value("${spring.rabbitmq.exchange_name}")private String exchangeName;@Value("${spring.rabbitmq.routing_key}")private String routingKey;// use RabbitTemplate to send the messages. it auto config for us, we just need to inject and use it.private final RabbitTemplate rabbitTemplate;private static final Logger LOGGER = LoggerFactory.getLogger(RabbitMQJsonProducer.class);public RabbitMQJsonProducer(RabbitTemplate rabbitTemplate) {this.rabbitTemplate = rabbitTemplate;}public void sendJsonMessage(User user) {LOGGER.info(String.format("Message sent => %s", user.toString()));rabbitTemplate.convertAndSend(exchangeName, routingKey, user);}
}

Create API to send json object

// file path: com/fan/springbootrabbitmq/publisher/RabbitMQJsonProducer.java
package com.fan.springbootrabbitmq.publisher;import com.fan.springbootrabbitmq.dto.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;@Service
public class RabbitMQJsonProducer {@Value("${spring.rabbitmq.exchange_name}")private String exchangeName;@Value("${spring.rabbitmq.json.routing_key}")private String routingJsonKey;// use RabbitTemplate to send the messages. it auto config for us, we just need to inject and use it.private final RabbitTemplate rabbitTemplate;private static final Logger LOGGER = LoggerFactory.getLogger(RabbitMQJsonProducer.class);public RabbitMQJsonProducer(RabbitTemplate rabbitTemplate) {this.rabbitTemplate = rabbitTemplate;}public void sendJsonMessage(User user) {LOGGER.info(String.format("Message sent => %s", user.toString()));rabbitTemplate.convertAndSend(exchangeName, routingJsonKey, user);}
}

Consum json message

file path: com/fan/springbootrabbitmq/publisher/RabbitMQJsonConsumer.java
package com.fan.springbootrabbitmq.publisher;import com.fan.springbootrabbitmq.dto.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;@Service
public class RabbitMQJsonConsumer {private static final Logger LOGGER = LoggerFactory.getLogger(RabbitMQProducer.class);@RabbitListener(queues = "${spring.rabbitmq.json.queue_name}")public void consum(User user) {LOGGER.info(String.format("Message received => %s", user.toString()));}}

http://www.ppmy.cn/news/68010.html

相关文章

filter和handlerInterceptor的各个方法执行的排序

Filter和HandlerInterceptor的方法执行顺序如下&#xff1a; Filter 在请求进入Servlet容器之前&#xff0c;先经过Filter的过滤器链。Filter的init()方法只会在容器启动时执行一次。Filter的doFilter()方法是每次请求都会执行的&#xff0c;如果需要放行请求&#xff0c;需要…

搭建高效微服务架构:Kubernetes、Prometheus和ELK Stack的完美组合

搭建高效微服务架构&#xff1a;Kubernetes、Prometheus和ELK Stack的完美组合 一、前言1 微服务架构简介2 Kubernetes 简介3 Kubernetes 与微服务 二、准备工作1 安装 Kubernetes1.1 搭建 Kubernetes 集群1.2 安装 kubectl 工具 2 准备 Docker 镜像2.1 编写 Dockerfile 文件2.…

华为OD机试(21-40)老题库解析Java源码系列连载ing

华为OD机试算法题新老题库练习及源码 老题库21.字符串序列判定22.最长的指定瑕疵度的元音子串 郑重声明&#xff1a; 1.博客中涉及题目为网上搜索而来&#xff0c;若侵权&#xff0c;请联系作者删除。 源码内容为个人原创&#xff0c;仅允许个人学习使用。 2.博客中涉及的源…

多优先级(笔记)

目录 支持多优先级的方法通用方法优化方法1、修改任务控制块2、修改xTaskCerateStactic()修改 prvInitialiseNewTask() 函数prvAddTaskToReadyList()初始化任务列表prvAddTaskToReadyList()vTaskStartScheduler()vTaskDelay()vTaskSwitchContext()xTaskIncrementTick() 实验实验…

Java EE 进阶---多线程(一)

目录 一、常见的锁策略 乐观锁 vs 悲观锁 重量级锁 vs 轻量级锁 读写锁&#xff06;普通互斥锁 自旋锁&#xff06;挂起等待锁 可重入锁&#xff06;不可重入锁 公平锁&#xff06;非公平锁 synchronized实现了哪些锁策略&#xff1f; 二、Compare And Swap 比较并交换…

swift语言特性,swift语法介绍,swift使用技巧

Swift语言特性、Swift语法介绍、Swift使用技巧 Swift是一种由苹果公司开发的编程语言&#xff0c;于2014年首次发布。它是一种现代、快速、安全的编程语言&#xff0c;用于iOS、macOS、watchOS和tvOS应用程序的开发。Swift语言具有许多特性和优点&#xff0c;使得它成为一种非…

【Tkinter.Floodgauge】当程序需要长时间运行,可以用这个组件显示进度【文末附源码地址】

文章目录 效果展示源码解析导包Floodgauge组件界面初始化创建窗口修改数值运行 源码地址 效果展示 我在使用tkinter进行界面化操作的时候&#xff0c;会遇到运行很慢的程序&#xff0c;比如&#xff1a;爬虫下载视频、压缩解压文件&#xff0c;这些操作会很耗时间。 Floodgau…

DNDC模型在土地利用变化、未来气候变化下的建模方法及温室气体时空动态模拟

由于全球变暖、大气中温室气体浓度逐年增加等问题的出现&#xff0c;“双碳”行动特别是碳中和已经在世界范围形成广泛影响。“十四五”时期&#xff0c;我国生态文明建设进入了以降碳为重点战略方向、推动减污降碳协同增效、促进经济社会发展全面绿色转型、实现生态环境质量改…