spring配置RabbitMQ的发送和接收demo
首先,整个demo包含6个文件:
spring-rabbitmq.xml:配置rabbitmq的queue,exchange,已经发送和接受的bean;
MQProducer.java:发送消息到指定队列的接口;
MQProducerImpl.java:发送消息到指定队列的实现类;
QueueListenter.java:监听queue消息并接收消费;
TestQueue.java:测试类;
sys.properties:配置rabbitmq的地址,账户,密码,端口等
具体内容如下:
1、spring-rabbitmq.xml
<?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: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.xsd
http://www.springframework.org/schema/rabbit
http://www.springframework.org/schema/rabbit/spring-rabbit-1.6.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.1.xsd">
<description>rabbitmq 连接服务配置</description>
<!-- 基于注解的根包扫描路径 -->
<context:component-scan base-package="com.mdl.activemq" />
<context:component-scan base-package="com.mdl.activemq.services" />
<!-- 加载内网系统配置 -->
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="properties" ref="configProperties" />
</bean>
<bean id="configProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="locations">
<list>
<value>classpath:sys.properties</value>
</list>
</property>
</bean>
<!-- 消息对象json转换类 -->
<bean id="jsonMessageConverter" class="org.springframework.amqp.support.converter.Jackson2JsonMessageConverter" />
<!-- 连接配置 -->
<rabbit:connection-factory id="connectionFactory" host="${mq.host}" username="${mq.username}" password="${mq.password}" port="5672" />
<rabbit:admin connection-factory="connectionFactory"/>
<!-- spring template声明-->
<rabbit:template id="amqpTemplate" exchange="xk-test-mq-exchange" connection-factory="connectionFactory" message-converter="jsonMessageConverter"/>
<!-- 声明一个Que -->
<!-- durable:是否持久化 ; exclusive: 仅创建者可以使用的私有队列,断开后自动删除; auto_delete: 当所有消费客户端连接断开后,是否自动删除队列 -->
<rabbit:queue id="xk_test_queue" name="xk_test_queue" durable="true" auto-delete="false" exclusive="false" />
<!-- 声明一个Exchange -->
<rabbit:direct-exchange name="xk-test-mq-exchange" durable="true" auto-delete="false" id="xk-test-mq-exchange">
<rabbit:bindings>
<rabbit:binding queue="xk_test_queue" key="xk_test_queue"/>
</rabbit:bindings>
</rabbit:direct-exchange>
<!--
rabbit:direct-exchange:定义exchange模式为direct,意思就是消息与一个特定的路由键完全匹配,才会转发。
rabbit:binding:设置消息queue匹配的key
-->
<!-- 监听器 -->
<bean id="queueListenter" class="com.mdl.activemq.listener.QueueListenter"/>
<!-- 配置监听queue -->
<rabbit:listener-container connection-factory="connectionFactory" acknowledge="auto">
<rabbit:listener queues="xk_test_queue" ref="queueListenter"/>
</rabbit:listener-container>
</beans>
2、MQProducer.java
package com.mdl.activemq.services;
public interface MQProducer {
/**
* 发送消息到指定队列
* @param queueKey
* @param object
*/
void sendDataToQueue(String queueKey, Object object);
}
3、MQProducerImpl.java
package com.mdl.activemq.services.impl;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.mdl.activemq.services.MQProducer;
//或者@Repository
@Service
public class MQProducerImpl implements MQProducer {
@Autowired
private AmqpTemplate amqpTemplate;
@Override
public void sendDataToQueue(String queueKey, Object object) {
try {
System.out.println("=========发送消息开始=============消息:" + object.toString());
amqpTemplate.convertAndSend(queueKey, object);
} catch (Exception e) {
e.printStackTrace();
}
}
}
4、QueueListenter.java
package com.mdl.activemq.listener;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageListener;
public class QueueListenter implements MessageListener {
@Override
public void onMessage(Message message) {
String str = "";
try
{
str = new String(message.getBody(), "UTF-8");
System.out.println("=============监听【QueueListenter】消息"+message);
System.out.print("=====获取消息"+str);
}catch(Exception e)
{
e.printStackTrace();
}
}
}
5、sys.properties
#rabbitmq
mq.host=172.29.231.70
mq.username=admin
mq.password=admin
mq.port=5672
结果:
log4j:WARN No appenders could be found for logger (org.springframework.test.context.junit4.SpringJUnit4ClassRunner).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
=========发送消息开始=============消息:{data=hello,rabbmitmq!}
=============监听【QueueListenter】消息(Body:'{"data":"hello,rabbmitmq!"}' MessageProperties [headers={__ContentTypeId__=java.lang.Object, __KeyTypeId__=java.lang.Object, __TypeId__=java.util.HashMap}, timestamp=null, messageId=null, userId=null, receivedUserId=null, appId=null, clusterId=null, type=null, correlationId=null, correlationIdString=null, replyTo=null, contentType=application/json, contentEncoding=UTF-8, contentLength=0, deliveryMode=null, receivedDeliveryMode=PERSISTENT, expiration=null, priority=0, redelivered=false, receivedExchange=xk-test-mq-exchange, receivedRoutingKey=xk_test_queue, receivedDelay=null, deliveryTag=1, messageCount=0, consumerTag=amq.ctag-fPcPLEkIxiq0zUgwvOP_eQ, consumerQueue=xk_test_queue])
=====获取消息{"data":"hello,rabbmitmq!"}