本篇文章实现了 SpringBoot整合RabbitMQ,实现了 work模型,发布订阅模型,topic模型,confirm消息确认机制,return消息机制,TTL队列,死信队列等。
整合方式有很多,比如使用 RabbitAdmin进行整合,本文介绍一个最简单的整合方式,只需要在 RabbitmqConfig.java 配置文件中进行简单配置,便可以方便的使用。相信你会喜欢这种方式的。
pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-amqpartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<optional>trueoptional>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
<scope>testscope>
dependency>
dependencies>
application.properties
# 应用名
spring.application.name=springboot-rabbitmq
# rabbitmq配置信息
# ip
spring.rabbitmq.host=rabbitmq服务器的ip
# 端口
spring.rabbitmq.port=5672
# 用户名
spring.rabbitmq.username=kongming
# 密码
spring.rabbitmq.password=mima
# 配置虚拟机
spring.rabbitmq.virtual-host=/
# 消息开启手动确认
spring.rabbitmq.listener.direct.acknowledge-mode=manual
User.java
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User implements Serializable {
private static final long serialVersionUID = 8142836626401616290L;
private Integer id;
private String name;
private String password;
}
RabbitmqConfig.java
@SpringBootConfiguration
public class RabbitmqConfig {
// 配置一个工作模型队列
@Bean
public Queue queueWork1() {
return new Queue("queue_work");
}
}
RabbitmqController.java
@RestController
public class RabbitmqController {
@Autowired
private RabbitmqService rabbitmqService;
@RequestMapping("/sendWork")
public Object sendWork() {
rabbitmqService.sendWork();
return "发送成功...";
}
}
RabbitmqServiceImpl.java
@Service
public class RabbitmqServiceImpl implements RabbitmqService {
@Autowired
private RabbitmqMapper rabbitmqMapper;
@Override
public void sendWork() {
rabbitmqMapper.sendWork();
}
}
RabbitmqMapper.java
@Component
public class RabbitmqMapper {
@Autowired
private RabbitTemplate rabbitTemplate;
public void sendWork() {
for (int i = 0; i < 10; i++) {
rabbitTemplate.convertAndSend("queue_work", "测试work模型: " + i);
}
}
}
WorkReceiveListener.java
// 2个消费者
@Component
public class WorkReceiveListener {
@RabbitListener(queues = "queue_work")
public void receiveMessage(String msg, Channel channel, Message message) {
// 只包含发送的消息
System.out.println("1接收到消息:" + msg);
// channel 通道信息
// message 附加的参数信息
}
@RabbitListener(queues = "queue_work")
public void receiveMessage2(Object obj, Channel channel, Message message) {
// 包含所有的信息
System.out.println("2接收到消息:" + obj);
}
}
访问 http://127.0.0.1:8080/sendWork,输出如下数据
RabbitmqConfig.java
// 发布订阅模式
// 声明两个队列
@Bean
public Queue queueFanout1() {
return new Queue("queue_fanout1");
}
@Bean
public Queue queueFanout2() {
return new Queue("queue_fanout2");
}
// 准备一个交换机
@Bean
public FanoutExchange exchangeFanout() {
return new FanoutExchange("exchange_fanout");
}
// 将交换机和队列进行绑定
@Bean
public Binding bindingExchange1() {
return BindingBuilder.bind(queueFanout1()).to(exchangeFanout());
}
@Bean
public Binding bindingExchange2() {
return BindingBuilder.bind(queueFanout2()).to(exchangeFanout());
}
RabbitmqController.java
@RequestMapping("/sendPublish")
public String sendPublish() {
rabbitmqService.sendPublish();
return "发送成功...";
}
RabbitmqServiceImpl.java
@Override
public void sendPublish() {
rabbitmqMapper.sendPublish();
}
RabbitmqMapper.java
// 向发布订阅模式里面发送消息
public void sendPublish() {
for (int i = 0; i < 5; i++) {
// rabbitTemplate.convertSendAndReceive("exchange_fanout", "", "测试发布订阅模型:" + i);
rabbitTemplate.convertAndSend("exchange_fanout", "", "测试发布订阅模型:" + i);
}
}
PublishReceiveListener.java
@Component
public class PublishReceiveListener {
@RabbitListener(queues = "queue_fanout1")
public void receiveMsg1(String msg) {
System.out.println("队列1接收到消息:" + msg);
}
@RabbitListener(queues = "queue_fanout2")
public void receiveMsg2(String msg) {
System.out.println("队列2接收到消息:" + msg);
}
}
测试结果
http://localhost:8080/sendPublish
使用 convertAndSend 方法时的结果:输出时没有顺序,不需要等待,直接运行
使用 convertSendAndReceive 方法时的结果:按照一定的顺序,只有确定消费者接收到消息,才会发送下一条信息,每条消息之间会有间隔时间
RabbitTemplate中convertSendAndReceive方法与convertAndSend方法的区别
RabbitmqConfig.java
// topic 模型
@Bean
public Queue queueTopic1() {
return new Queue("queue_topic1");
}
@Bean
public Queue queueTopic2() {
return new Queue("queue_topic2");
}
@Bean
public TopicExchange exchangeTopic() {
return new TopicExchange("exchange_topic");
}
@Bean
public Binding bindingTopic1() {
return BindingBuilder.bind(queueTopic1()).to(exchangeTopic()).with("topic.#");
}
@Bean
public Binding bindingTopic2() {
return BindingBuilder.bind(queueTopic2()).to(exchangeTopic()).with("topic.*");
}
RabbitmqController.java
@RequestMapping("/sendTopic")
public String sendTopic() {
rabbitmqService.sendTopic();
return "发送成功...";
}
RabbitmqServiceImpl.java
@Override
public void sendTopic() {
rabbitmqMapper.sendTopic();
}
RabbitmqMapper.java
// 向topic模型发送数据
public void sendTopic() {
for (int i = 0; i < 10; i++) {
if (i % 2 == 0) {
rabbitTemplate.convertSendAndReceive("exchange_topic", "topic.km.topic", "测试发布订阅模型:" + i);
} else {
rabbitTemplate.convertSendAndReceive("exchange_topic", "topic.km", "测试发布订阅模型:" + i);
}
}
}
TopicReceiveListener.java
@Component
public class TopicReceiveListener {
@RabbitListener(queues = "queue_topic1")
public void receiveMsg1(String msg) {
System.out.println("消费者1接收到:" + msg);
}
@RabbitListener(queues = "queue_topic2")
public void receiveMsg2(String msg) {
System.out.println("消费者2接收到:" + msg);
}
}
测试结果
可以看出来,消费者1 接收到了所有的数据,消费者2只接受到了一半(奇数)的数据
application.properties
# 开启消息确认机制 confirm 异步
spring.rabbitmq.publisher-confirm-type=correlated
# 之前的旧版本 开启消息确认机制的方式
# spring.rabbitmq.publisher-confirms=true
# 消息开启手动确认
spring.rabbitmq.listener.direct.acknowledge-mode=manual
RabbitmqConfig.java
// 测试confirm 机制,专门创建了一个队列
@Bean
public Queue queueConfirm() {
return new Queue("queue_confirm");
}
RabbitmqController.java
@RequestMapping("/sendConfirm")
public String sendConfirm() {
rabbitmqService.sendConfirm();
return "发送成功...";
}
RabbitmqServiceImpl.java
@Override
public void sendConfirm() {
rabbitmqMapper.sendConfirm();
}
RabbitmqMapper.java
// 配置 confirm 机制
private final RabbitTemplate.ConfirmCallback confirmCallback = new RabbitTemplate.ConfirmCallback() {
/**
* @param correlationData 消息相关的数据,一般用于获取 唯一标识 id
* @param b true 消息确认成功,false 失败
* @param s 确认失败的原因
*/
@Override
public void confirm(CorrelationData correlationData, boolean b, String s) {
if (b) {
System.out.println("confirm 消息确认成功..." + correlationData.getId());
} else {
System.out.println("confirm 消息确认失败..." + correlationData.getId() + " cause: " + s);
}
}
};
// 测试 confirm机制
public void sendConfirm() {
rabbitTemplate.convertAndSend("queue_confirm", new User(1, "km", "km123"), new CorrelationData("" + System.currentTimeMillis()));
rabbitTemplate.setConfirmCallback(confirmCallback);
}
ConfirmReceiveListener.java
@Component
public class ConfirmReceiveListener {
@RabbitListener(queues = "queue_confirm")
public void receiveMsg(User user) {
System.out.println("接收到的消息为:" + user);
}
}
测试结果
http://localhost:8080/sendConfirm
注意
使用confirm机制时,发送消息时最好把CorrelationData
加上,因为如果出错了,使用 CorrelationData
可以更快的定位到错误信息
application.properties
# 开启return机制
spring.rabbitmq.publisher-returns=true
# 消息开启手动确认
spring.rabbitmq.listener.direct.acknowledge-mode=manual
RabbitmqConfig.java
// 测试return机制
@Bean
public Queue queueReturn() {
return new Queue("queue_return");
}
@Bean
public TopicExchange exchangeReturn() {
return new TopicExchange("exchange_return");
}
@Bean
public Binding bindingReturn() {
return BindingBuilder.bind(queueReturn()).to(exchangeReturn()).with("return.*");
}
RabbitmqController.java
@RequestMapping("/sendReturn")
public String sendReturn() {
rabbitmqService.sendReturn();
return "发送成功...";
}
RabbitmqServiceImpl.java
@Override
public void sendReturn() {
rabbitmqMapper.sendReturn();
}
RabbitmqMapper.java
// 配置 return 消息机制
private final RabbitTemplate.ReturnCallback returnCallback = new RabbitTemplate.ReturnCallback() {
/**
* return 的回调方法(找不到路由才会触发)
* @param message 消息的相关信息
* @param i 错误状态码
* @param s 错误状态码对应的文本信息
* @param s1 交换机的名字
* @param s2 路由的key
*/
@Override
public void returnedMessage(Message message, int i, String s, String s1, String s2) {
System.out.println(message);
System.out.println(new String(message.getBody()));
System.out.println(i);
System.out.println(s);
System.out.println(s1);
System.out.println(s2);
}
};
// 测试return机制
public void sendReturn() {
rabbitTemplate.setReturnCallback(returnCallback);
rabbitTemplate.convertAndSend("exchange_return", "return.km.km", "测试 return 机制");
// rabbitTemplate.convertAndSend("exchange_return", "return.km", "测试 return 机制");
}
ReturnReceiveListener.java
@Component
public class ReturnReceiveListener {
@RabbitListener(queues = "queue_return")
public void receiveMsg(String msg) {
System.out.println("接收的消息为:" + msg);
}
}
测试结果
使用正确的路由:return.km
TTL队列、死信队列和普通队列的用法是一致的,这里只说明其创建方式
RabbitmqConfig.java
// TTL 队列
@Bean
public Queue queueTTL() {
Map<String, Object> map = new HashMap<>(1);
map.put("x-message-ttl", 10000);
return new Queue("queue_ttl", true, false, false, map);
}
// 产生死信的队列
@Bean
public Queue queueDLX() {
Map<String, Object> map = new HashMap<>(2);
// 5秒后,消息自动变为死信
map.put("x-message-ttl", 5000);
map.put("x-dead-letter-exchange", "exchange_receive");
map.put("x-dead-letter-routing-key", "receive_key");
return new Queue("queue_dlx", true, false, false, map);
}
// 死信交换机
@Bean
public DirectExchange exchangeDLX() {
return new DirectExchange("exchange_dlx");
}
// 给死信队列绑定交换机
@Bean
public Binding bindingDLX() {
return BindingBuilder.bind(queueDLX()).to(exchangeDLX()).with("receive_key");
}
// 死信接收交换机
@Bean
public DirectExchange exchangeReceive() {
return new DirectExchange("exchange_receive");
}
// 接收死信的队列
@Bean
public Queue queueReceive() {
return new Queue("queue_receive");
}
// 将交换机与队列绑定
@Bean
public Binding bindingReceive() {
return BindingBuilder.bind(queueReceive()).to(exchangeReceive()).with("receive_key");
}
测试
启动项目后,队列和交换机已经初始化完毕,可前往 http://rabbitmqip:15672/ 自行验证死信队列以及TTL队列
点击 dlx 交换机
输入 key 和要发送的值,publish
刚开始,queue_dlx 中有一条数据,5秒后,消息变成死信,自动转移到 queue_receive 中
本文若有错误,还请各路大佬指正指正!