RabbitMQ与Spring集成
1.与Spring集成
1.1 pom文件
1.2 spring配置文件
配置文件中增加命名空间
连接相关配置
生产者配置
RabbitTemplate
或下面这种声明方式也是可以的。
队列和交换器
可以在生产者配置文件中增加队列和交换器
消费者配置
队列和交换器
消费者中也可配置队列和交换器,以及指定队列和交换器绑定的路由键
消费者bean
或
监听容器
将消费者bean和队列联系起来
代码:消费者实现MessageListener接口即可。
2.示例
2.1 生产者
Spring 配置文件
<?xml version="1.0" encoding="UTF-8"?>
<!-- 查找最新的schemaLocation 访问 http://www.springframework.org/schema/ -->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:rabbit="http://www.springframework.org/schema/rabbit"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/rabbit
http://www.springframework.org/schema/rabbit/spring-rabbit-2.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 配置扫描路径 -->
<context:component-scan base-package="com.zava">
<!-- 只扫描Service,也可以添加Repostory,但是要把Controller排除在外,Controller由spring-mvc.xml去加载 -->
<!-- <context:include-filter type="annotation" expression="org.springframework.stereotype.Service" /> -->
<!-- <context:include-filter type="annotation" expression="org.springframework.stereotype.Repository" /> -->
<!-- <context:include-filter type="annotation" expression="org.springframework.stereotype.Component" /> -->
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
</context:component-scan>
<!-- rabbitMQ配置 -->
<bean id="rabbitConnectionFactory" class="org.springframework.amqp.rabbit.connection.CachingConnectionFactory">
<constructor-arg value="127.0.0.1" />
<property name="username" value="guest"/>
<property name="password" value="guest" />
<property name="channelCacheSize" value="8"/>
<property name="port" value="5672" />
</bean>
<!--Spring的rabbitmq admin-->
<rabbit:admin connection-factory="rabbitConnectionFactory"/>
<!-- 创建rabbitTemplate 消息模板类 -->
<bean id="rabbitTemplate" class="org.springframework.amqp.rabbit.core.RabbitTemplate">
<constructor-arg ref="rabbitConnectionFactory" />
</bean>
bean
<!--生产者创建队列-->
<rabbit:queue name="h1_queue" durable="false" />
<rabbit:queue name="h2_queue" durable="false" />
<rabbit:queue name="h3_queue" durable="false" />
<!--fanout交换器-->
<rabbit:fanout-exchange name="fanout-exchange" durable="false" xmlns="http://www.springframework.org/schema/rabbit">
<rabbit:bindings>
<rabbit:binding queue="h1_queue"></rabbit:binding>
<rabbit:binding queue="h2_queue"></rabbit:binding>
<rabbit:binding queue="h3_queue"></rabbit:binding>
</rabbit:bindings>
</rabbit:fanout-exchange>
</beans>
发送消息
package com.zava.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* @Author: Rab
* @Date: 2020-04-16 17:56
* @Description:
*/
@Controller
@RequestMapping("/rabbitmq")
public class RabbitMqController {
private Logger logger = LoggerFactory.getLogger(RabbitMqController.class);
@Autowired
RabbitTemplate rabbitTemplate;
@ResponseBody
@RequestMapping("/fanoutSender")
public String fanoutSender(@RequestParam("message") String message) {
String opt = "";
try {
for (int i = 0; i < 3; i++) {
String str = "Fanout,the message_" + i + " is : " + message;
logger.info("**************************Send Message:[" + str + "]");
//发送消息
rabbitTemplate.send("fanout-exchange", "test", new Message(str.getBytes(), new MessageProperties()));
}
opt = "suc";
} catch (Exception e) {
}
return opt;
}
@ResponseBody
@RequestMapping("/topicSender")
public String topicSender(@RequestParam("message") String message) {
String opt = "";
try {
String[] severities = {"error", "info", "warning"};
String[] modules = {"email", "order", "user"};
for (int i = 0; i < severities.length; i++) {
for (int j = 0; j < modules.length; j++) {
String routeKey = severities[i] + "." + modules[j];
String str = "Topic,the message_[" + i + "," + j + "] is [rk:" + routeKey + "][msg:" + message + "]";
logger.info("**************************Send Message:[" + str + "]");
MessageProperties messageProperties = new MessageProperties();
rabbitTemplate.send("topic_exchange",
routeKey,
new Message(str.getBytes(), messageProperties));
}
}
opt = "suc";
} catch (Exception e) {
opt = e.getCause().toString();
}
return opt;
}
}
2.2 消费者
spring配置文件
<?xml version="1.0" encoding="UTF-8"?>
<!-- 查找最新的schemaLocation 访问 http://www.springframework.org/schema/ -->
<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-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/rabbit
http://www.springframework.org/schema/rabbit/spring-rabbit-2.0.xsd">
<!-- 配置扫描路径 -->
<context:component-scan base-package="com.zava">
<!-- 只扫描Service,也可以添加Repostory,但是要把Controller排除在外,Controller由spring-mvc.xml去加载 -->
<!-- <context:include-filter type="annotation" expression="org.springframework.stereotype.Service" /> -->
<!-- <context:include-filter type="annotation" expression="org.springframework.stereotype.Repository" /> -->
<!-- <context:include-filter type="annotation" expression="org.springframework.stereotype.Component" /> -->
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!-- rabbitMQ配置 -->
<bean id="rabbitConnectionFactory"
class="org.springframework.amqp.rabbit.connection.CachingConnectionFactory">
<constructor-arg value="127.0.0.1"/>
<property name="username" value="guest"/>
<property name="password" value="guest"/>
<property name="channelCacheSize" value="8"/>
<property name="port" value="5672"></property>
</bean>
<rabbit:admin connection-factory="rabbitConnectionFactory"/>
<!-- fanout交换器 begin-->
<!-- 定义队列 -->
<rabbit:queue name="h1_queue" durable="false"/>
<rabbit:queue name="h2_queue" durable="false"/>
<rabbit:queue name="h3_queue" durable="false"/>
<!-- 把需要数据的队列与交换器绑定一起 -->
<rabbit:fanout-exchange name="fanout-exchange"
xmlns="http://www.springframework.org/schema/rabbit" durable="false">
<rabbit:bindings>
<rabbit:binding queue="h1_queue"></rabbit:binding>
<rabbit:binding queue="h2_queue"></rabbit:binding>
<rabbit:binding queue="h3_queue"></rabbit:binding>
</rabbit:bindings>
</rabbit:fanout-exchange>
<!-- fanout交换器 end-->
<!-- topic交换器 begin-->
<!-- 定义队列 -->
<rabbit:queue name="all_log_queue" durable="false"/>
<rabbit:queue name="email_all_queue" durable="false"/>
<rabbit:queue name="email_error_queue" durable="false"/>
<rabbit:queue name="all_error_queue" durable="false"/>
<!-- 把需要数据的队列通过路由键与topic交换器绑定一起 -->
<rabbit:topic-exchange name="topic-exchange"
xmlns="http://www.springframework.org/schema/rabbit" durable="false">
<rabbit:bindings>
<binding pattern="#" queue="all_log_queue"></binding>
<binding pattern="*.email" queue="email_all_queue"></binding>
<binding pattern="error.email" queue="email_error_queue"></binding>
<binding pattern="error.*" queue="all_error_queue"></binding>
</rabbit:bindings>
</rabbit:topic-exchange>
<!-- topic交换器 end-->
<!--消费者定义-->
<bean id="h1_Service" class="com.zava.service.fanout.H1_Service">
</bean>
<bean id="h2_Service" class="com.zava.service.fanout.H2_Service">
</bean>
<bean id="h3_Service" class="com.zava.service.fanout.H3_Service">
</bean>
<!--监听容器-->
<rabbit:listener-container connection-factory="rabbitConnectionFactory">
<rabbit:listener ref="h1_Service" queues="h1_queue"
method="onMessage"/>
<rabbit:listener ref="h2_Service" queues="h2_queue"
method="onMessage"/>
<rabbit:listener ref="h3_Service" queues="h3_queue"
method="onMessage"/>
<rabbit:listener ref="allLogTopicService" queues="all_log_queue"
method="onMessage"/>
<rabbit:listener ref="emailAllTopicService" queues="email_all_queue"
method="onMessage"/>
<rabbit:listener ref="emailErrorTopicService" queues="email_error_queue"
method="onMessage"/>
<rabbit:listener ref="allErrorTopicService" queues="all_error_queue"
method="onMessage"/>
</rabbit:listener-container>
</beans>
接收消息:fanout类型
package com.zava.service.fanout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageListener;
/**
* @Author: Rab
* @Date: 2020-04-16 18:27
* @Description:
*/
public class H1_Service implements MessageListener {
private Logger logger = LoggerFactory.getLogger(H1_Service.class);
@Override
public void onMessage(Message message) {
logger.info("Get message: "+new String( message.getBody()));
}
}
接收消息:Topic类型
package com.zava.service.topic;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageListener;
import org.springframework.stereotype.Component;
/**
*/
@Component
public class EmailErrorTopicService implements MessageListener {
private Logger logger = LoggerFactory.getLogger(EmailErrorTopicService.class);
public void onMessage(Message message) {
logger.info("Get message: "+new String( message.getBody()));
}
}