SpringBoot整合RabbitMQ
Posted 鼓捣猫腻
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SpringBoot整合RabbitMQ相关的知识,希望对你有一定的参考价值。
一、创建项目并导入依赖
<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>
二、相关配置和代码
2.1)application.properties
spring.rabbitmq.host=192.168.21.136
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
spring.rabbitmq.port=5672
2.2)RabbitMQ消息路由四种策略
不了解RabbitMQ的强烈建议去看一下理论https://blog.csdn.net/qq_35953966/article/details/104054306
Direct和Topic类型的Exchange依赖routingkey与bindingkey的匹配规则来路由消息
Fanout和Headers类型的Exchange依赖routingkey与bindingkey的匹配规则来路由消息
2.2.1.1)创建RabbitDirectConfig配置类
该类主要是将Queue和Exchange绑定在一起,让Exchange根据消息生产者的routingkey和消息消费者的routingkey匹配,再将消息发到对应消息消费者那里
public class RabbitDirectConfig{
public final static String DIRECTNAME="fern_direct";
DirectExchange directExchange(){
//durable是重启后是否依然有效,autoDelete长期没有使用是否删除掉
return new DirectExchange(DIRECTNAME,true,false);
//将queue|队列和directExchange绑定在一起
return BindingBuilder.bind(queue()).to(directExchange()).with("direct");
@RabbitListener(queues="queue")
public void receive1(String msg){
System.out.println("handler1>>>>>>>>>>>>>>"+msg);
备注:Direct还有一种写法可以省略掉Exchange与Queue的绑定,只限Direct
publicclassRabbitFanoutConfig{
public final static String FANOUTNAME="fern_fanout";
return new Queue("queue_one");
return new Queue("queue_two");
FanoutExchange fanoutExchange(){
return new FanoutExchange(FANOUTNAME,true,false);
return BindingBuilder.bind(queueOne()).to(fanoutExchange());
return BindingBuilder.bind(queueTwo()).to(fanoutExchange());
@RabbitListener(queues="queue_one")
public void receive1(String msg){
System.out.println("FanoutReceiver:receive1>>>>>>>>>"+msg);
@RabbitListener(queues="queue_two")
public void receive2(String msg){
System.out.println("FanoutReceiver:receive2>>>>>>>>>"+msg);
public class RabbitTopicConfig{
public final static String TOPICNAME="fern_topic";
return new Queue("queue_xiaomi");
return newQueue("queue_huawei");
return newQueue("queue_iphone");
TopicExchange topicExchange(){
return newTopicExchange(TOPICNAME,true,false);
return BindingBuilder.bind(queue_xiaomi()).to(topicExchange()).with("xiaomi.*.*");
return BindingBuilder.bind(queue_huawei()).to(topicExchange()).with("huawei.#");
return BindingBuilder.bind(queue_iphone()).to(topicExchange()).with("#.iphone.#");
@RabbitListener(queues="queue_xiaomi")
public void receive1(String msg){
System.out.println("小米:"+msg);
@RabbitListener(queues="queue_huawei")
public void receive2(String msg){
System.out.println("华为:"+msg);
@RabbitListener(queues="queue_iphone")
public void receive3(String msg){
System.out.println("苹果:"+msg);
[SpringBoot系列]SpringBoot如何整合SSMP
SpringBoot完成SSM整合之SpringBoot整合junit