spring 版本4.2.0,rabbitmq版本3.5.6
需要三个jar包,分别是 spring-rabbit-1.5.1.RELEASE.jar,spring-amqp-1.5.1.RELEASE.jar,rabbitmq-client.jar
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: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
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/rabbit
http://www.springframework.org/schema/rabbit/spring-rabbit-1.0.xsd">
<!-- 连接服务配置 -->
<rabbit:connection-factory id="connectionFactory" host="localhost" username="guest" password="guest" port="5672" channel-cache-size="3" />
<rabbit:admin connection-factory="connectionFactory" />
<!-- queue 队列声明 -->
<rabbit:queue id="queuelp" name="queuelp" durable="true" auto-delete="false" exclusive="false" />
<rabbit:queue id="queuers" name="queuelp" durable="true" auto-delete="false" exclusive="false" />
<!-- direct-exchange 交换机制声明 -->
<rabbit:direct-exchange id="directExchangeLp" name="directExchangeLp" >
<rabbit:bindings>
<rabbit:binding queue="queuelp" key="lp"/>
<rabbit:binding queue="queuers" key="rs"/>
</rabbit:bindings>
</rabbit:direct-exchange>
<!-- spring amqpTemplate声明 -->
<rabbit:template id="amqpTemplate" connection-factory="connectionFactory" exchange="directExchangeLp"/>
<!-- 消费者 -->
<bean id="consumerListener" class="com.sky.lp.rabbitmq.ConsumerListener" />
<rabbit:listener-container connection-factory="connectionFactory">
<rabbit:listener ref="consumerListener" method="receiveMessage" queue-names="queuelp,queuers" />
</rabbit:listener-container>
</beans>
消费者代码
package com.sky.lp.rabbitmq;
public class ConsumerListener {
public void receiveMessage(String msg) {
System.out.println("received msg:" + msg);
}
}
测试代码
public void testSpringWayRabbitMq() {
ClassPathXmlApplicationContext appCtx = new ClassPathXmlApplicationContext("spring-rabbitmq.xml");
AmqpTemplate amqpTemplate = appCtx.getBean("amqpTemplate", AmqpTemplate.class);
//给队列发送消息
String routingKey = "lp";
amqpTemplate.convertAndSend(routingKey, "给队列 queuelp 发送消息");
routingKey = "rs";
amqpTemplate.convertAndSend(routingKey, "给队列 queuers 发送消息");
}