Spring与SpringBoot对RabbitMQ的整合篇
Spring 整合RabbitMQ
搭建生产者工程
创建maven项目,添加依赖
重点是spring-rabbit依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>spring-rabbitmq-producer</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.1.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.amqp</groupId>
<artifactId>spring-rabbit</artifactId>
<version>2.1.8.RELEASE</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.1.7.RELEASE</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
配置整合
在resource文件夹下创建rabbitmq.properties连接参数等配置文件;
rabbitmq.host=192.168.237.128
rabbitmq.port=5672
rabbitmq.username=root
rabbitmq.password=root
rabbitmq.virtual-host=/savior
在resource文件夹下创建spring-rabbitmq-producer.xml 的spring配置文件;
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:rabbit="http://www.springframework.org/schema/rabbit"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/rabbit
http://www.springframework.org/schema/rabbit/spring-rabbit.xsd">
<!--加载配置文件-->
<context:property-placeholder location="classpath:rabbitmq.properties"/>
<!-- 定义rabbitmq connectionFactory -->
<rabbit:connection-factory id="connectionFactory" host="${rabbitmq.host}"
port="${rabbitmq.port}"
username="${rabbitmq.username}"
password="${rabbitmq.password}"
virtual-host="${rabbitmq.virtual-host}"/>
<!--定义管理交换机、队列-->
<rabbit:admin connection-factory="connectionFactory"/>
<!--定义持久化队列,不存在则自动创建;不绑定到交换机则绑定到默认交换机
默认交换机类型为direct,名字为:"",路由键为队列的名称
-->
<!--
id:bean的名称
name:queue的名称
auto-declare:自动创建
auto-delete:自动删除。 最后一个消费者和该队列断开连接后,自动删除队列
exclusive:是否独占
durable:是否持久化
-->
<rabbit:queue id="spring_queue" name="spring_queue" auto-declare="true"/>
<!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~广播;所有队列都能收到消息~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<!--定义广播交换机中的持久化队列,不存在则自动创建-->
<rabbit:queue id="spring_fanout_queue_1" name="spring_fanout_queue_1" auto-declare="true"/>
<!--定义广播交换机中的持久化队列,不存在则自动创建-->
<rabbit:queue id="spring_fanout_queue_2" name="spring_fanout_queue_2" auto-declare="true"/>
<!--定义广播类型交换机;并绑定上述两个队列-->
<rabbit:fanout-exchange id="spring_fanout_exchange" name="spring_fanout_exchange" auto-declare="true">
<rabbit:bindings>
<rabbit:binding queue="spring_fanout_queue_1" />
<rabbit:binding queue="spring_fanout_queue_2"/>
</rabbit:bindings>
</rabbit:fanout-exchange>
<!--<rabbit:direct-exchange name="aa" >
<rabbit:bindings>
<!–direct 类型的交换机绑定队列 key :路由key queue:队列名称–>
<rabbit:binding queue="spring_queue" key="xxx"></rabbit:binding>
</rabbit:bindings>
</rabbit:direct-exchange>-->
<!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~通配符;*匹配一个单词,#匹配多个单词 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<!--定义广播交换机中的持久化队列,不存在则自动创建-->
<rabbit:queue id="spring_topic_queue_star" name="spring_topic_queue_star" auto-declare="true"/>
<!--定义广播交换机中的持久化队列,不存在则自动创建-->
<rabbit:queue id="spring_topic_queue_well" name="spring_topic_queue_well" auto-declare="true"/>
<!--定义广播交换机中的持久化队列,不存在则自动创建-->
<rabbit:queue id="spring_topic_queue_well2" name="spring_topic_queue_well2" auto-declare="true"/>
<rabbit:topic-exchange id="spring_topic_exchange" name="spring_topic_exchange" auto-declare="true">
<rabbit:bindings>
<rabbit:binding pattern="savior.*" queue="spring_topic_queue_star"/>
<rabbit:binding pattern="savior.#" queue="spring_topic_queue_well"/>
<rabbit:binding pattern="savior.#" queue="spring_topic_queue_well2"/>
</rabbit:bindings>
</rabbit:topic-exchange>
<!--定义rabbitTemplate对象操作可以在代码中方便发送消息-->
<rabbit:template id="rabbitTemplate" connection-factory="connectionFactory"/>
</beans>
发送消息
创建测试类,在里面测试发送消息
利用rabbitTemplate调用convertAndSend根据不同模式的需求选取不同参数的重载方法
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring-rabbitmq-producer.xml")
public class ProducerTest {
//使用rabbitTemplate对象可以在代码中方便发送消息
@Autowired
RabbitTemplate rabbitTemplate;
//简单模式下的发消息
@Test
public void testHelloWorld(){
/**
* convertAndSend(String routingKey, Object object)
*
* 简单模式下 routingKey 路由键 即为队列的名字
* object 要发送的消息
*/
rabbitTemplate.convertAndSend("spring_queue","hello world spring~~~~");
}
//发布订阅模式下 fanout 的发消息
@Test
public void testFanout(){
/**
* convertAndSend(String exchange, String routingKey, Object object)
*
* 发布订阅模式 exchange 交换机的名字
* routingKey 路由键设为 "" 使用默认的
* object 要发送的消息
*/
rabbitTemplate.convertAndSend("spring_fanout_exchange","","spring fanout~~~~");
}
//通配符模式下 topic 的发消息
@Test
public void testTopic(){
/**
* convertAndSend(String exchange, String routingKey, Object object)
*
* 通配符模式 exchange 交换机的名字
* routingKey 符合它匹配规则的路由键
* object 要发送的消息
*/
rabbitTemplate.convertAndSend("spring_topic_exchange","savior.niu.bi","savior come on from spring~~`");
}
}
搭建消费者工程
添加依赖、创建配置文件rabbitmq.properties 这两个同上生产者
创建消息监听器
简单模式监听器
public class SpringQueueListener implements MessageListener {
@Override
public void onMessage(Message message) {
System.out.println(new String(message.getBody()));
}
}
广播模式监听器1
public class FanoutListener1 implements MessageListener {
@Override
public void onMessage(Message message) {
System.out.println(new String(message.getBody()));
}
}
创建spring-rabbitmq-consumer.xml (spring配置文件)
在配置文件中将创建的监听器和相对于需要监听的队列进行绑定
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:rabbit="http://www.springframework.org/schema/rabbit"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/rabbit
http://www.springframework.org/schema/rabbit/spring-rabbit.xsd">
<!--加载配置文件-->
<context:property-placeholder location="classpath:rabbitmq.properties"/>
<!-- 定义rabbitmq connectionFactory -->
<rabbit:connection-factory id="connectionFactory" host="${rabbitmq.host}"
port="${rabbitmq.port}"
username="${rabbitmq.username}"
password="${rabbitmq.password}"
virtual-host="${rabbitmq.virtual-host}"/>
<bean id="springQueueListener" class="com.duanping.rabbitmq.listener.SpringQueueListener"/>
<bean id="fanoutListener1" class="com.duanping.rabbitmq.listener.FanoutListener1"/>
<!-- <bean id="fanoutListener2" class="com.duanping.rabbitmq.listener.FanoutListener2"/>-->
<!-- <bean id="topicListenerStar" class="com.duanping.rabbitmq.listener.TopicListenerStar"/>
<bean id="topicListenerWell" class="com.duanping.rabbitmq.listener.TopicListenerWell"/>
<bean id="topicListenerWell2" class="com.duanping.rabbitmq.listener.TopicListenerWell2"/>-->
<!-- 将创建的监听器和相对于需要监听的队列进行绑定 -->
<rabbit:listener-container connection-factory="connectionFactory" auto-declare="true">
<rabbit:listener ref="springQueueListener" queue-names="spring_queue"/>
<rabbit:listener ref="fanoutListener1" queue-names="spring_fanout_queue_1"/><!--
<rabbit:listener ref="fanoutListener2" queue-names="spring_fanout_queue_2"/>
<rabbit:listener ref="topicListenerStar" queue-names="spring_topic_queue_star"/>
<rabbit:listener ref="topicListenerWell" queue-names="spring_topic_queue_well"/>
<rabbit:listener ref="topicListenerWell2" queue-names="spring_topic_queue_well2"/>-->
</rabbit:listener-container>
</beans>
之后只要一加载配置好消费者监听器的配置文件,消费者就会开始消费
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring-rabbitmq-consumer.xml")
public class ConsumerTest {
@Test
public void test1(){
boolean flag =true;
while (flag){
}
}
}
Spring Boot整合RabbitMQ
在Spring项目中,可以使用Spring-Rabbit去操作RabbitMQ
spring-rabbit
尤其是在spring boot项目中只需要引入对应的amqp启动器依赖即可,方便的使用RabbitTemplate发送消息,使用注解接收消息。
一般在开发过程中:
生产者工程:
-
application.yml文件配置RabbitMQ相关信息;
-
在生产者工程中编写配置类,用于创建交换机和队列,并进行绑定
-
注入RabbitTemplate对象,通过RabbitTemplate对象发送消息到交换机
消费者工程:
-
application.yml文件配置RabbitMQ相关信息
-
创建消息处理类,用于接收队列中的消息并进行处理
搭建生产者工程
利用springboot快速构建工程
然后在pom.xml中添加以下依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
配置RabbitMQ
配置文件
spring:
rabbitmq:
host: 192.168.237.128
port: 5672
username: root
password: root
virtual-host: /savior
绑定交换机和队列
创建RabbitMQ队列与交换机绑定的配置类
@Configuration
public class RabbitMQConfig {
public static final String EXCHANGE_NAME="boot_topic_exchange";
public static final String QUEUE_NAME="boot_queue";
//交换机
@Bean("bootExchange")
public Exchange bootExchange(){
/**
* 根据需求选取不同的交换机
* fanoutExchange
* directExchange
* topicExchange
*
* durable 是否持久化
*/
return ExchangeBuilder.topicExchange(EXCHANGE_NAME).durable(true).build();
}
//队列
@Bean("bootQueue")
public Queue bootQueue(){
return QueueBuilder.durable(QUEUE_NAME).build();
}
//将队列和交换机进行绑定 Binding
/*
1.知道哪个队列
2.知道哪个交换机
3.routing Key
*/
// 将来该配置中试着需求的增加 肯定会出现很多交换机和队列
// 所以我们应该使用 @Qualifier 注解来指定对应的队列和交换机进行绑定
@Bean
public Binding bindQueueExchange(@Qualifier("bootQueue") Queue queue, @Qualifier("bootExchange") Exchange exchange){
return BindingBuilder.bind(queue).to(exchange).with("boot.#").noargs();
}
}
发送消息
@SpringBootTest
class DemoApplicationTests {
@Autowired
RabbitTemplate rabbitTemplate;
@Test
public void test1(){
rabbitTemplate.convertAndSend(RabbitMQConfig.EXCHANGE_NAME,"boot.nice","springboot rabbitMQ~~~");
}
}
搭建消费者工程
添加依赖和生产者相同
创建application.yml
spring:
rabbitmq:
host: 192.168.237.128
port: 5672
username: root
password: root
virtual-host: /savior
消息监听处理类
// 记得注入到容器中 ,交由spring进行统一管理
@Component
public class RabbitMQListener {
/**
* 一定要记得使用 @RabbitListener注解 并且声明监听的队列
*
* @param message 封装所需的一系列消息
*/
@RabbitListener(queues = "boot_queue")
public void ListenerQueue(Message message){
System.out.println(new String(message.getBody()));
}
}
之后当主配置类只要一启动 监听器就会启动,消费者开始消费