rabbitMQ结合spring
1,添加依赖
<dependency>
<groupId>com.rabbitmq</groupId>
<artifactId>amqp-client</artifactId>
<version>4.3.0</version>
</dependency>
<dependency>
<groupId>org.springframework.amqp</groupId>
<artifactId>spring-rabbit</artifactId>
<version>1.4.5.RELEASE</version>
</dependency>
2,创建配置文件 rabbitmq-config.properties
//rabbitmq-config.properties mq.host=127.0.0.1 mq.username=admin mq.password=admin mq.port=5672 mq.vhost=/
3,创建配置文件 application-mq.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:rabbit="http://www.springframework.org/schema/rabbit"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/rabbit
http://www.springframework.org/schema/rabbit/spring-rabbit-1.0.xsd" >
<!--<description>rabbitmq 连接服务配置</description>-->
<context:property-placeholder ignore-unresolvable="true" location="classpath:/rabbitmq-config.properties"/>
<!-- 连接配置 -->
<rabbit:connection-factory id="connectionFactory" host="${mq.host}" username="${mq.username}" password="${mq.password}" port="${mq.port}" virtual-host="${mq.vhost}"/>
<rabbit:admin connection-factory="connectionFactory"/>
<!-- spring template声明-->
<rabbit:template exchange="amqpExchange" id="amqpTemplate" connection-factory="connectionFactory" message-converter="jsonMessageConverter" />
<!-- 消息对象json转换类 -->
<bean id="jsonMessageConverter" class="org.springframework.amqp.support.converter.Jackson2JsonMessageConverter" />
<rabbit:queue id="test_queue_key" name="test_queue_key" durable="true" auto-delete="false" exclusive="false" />
<rabbit:direct-exchange name="test-mq-exchange" durable="true" auto-delete="false" id="test-mq-exchange">
<rabbit:bindings>
<rabbit:binding queue="test_queue_key" key="test_queue_key"/>
</rabbit:bindings>
</rabbit:direct-exchange>
<bean id="queueListener" class="com.st.ws.command.main.rabbitmq.QueueListener"/>
<rabbit:listener-container connection-factory="connectionFactory" acknowledge="auto">
<rabbit:listener queues="test_queue_key" ref="queueListener"/>
</rabbit:listener-container>
</beans>
4,在配置文件applicationContext.xml中引入
<import resource="classpath*:application-mq.xml" />
5,创建监听
@Component
public class QueueListener extends BaseController implements MessageListener {
@Override
public void onMessage(Message msg) {
try{
logger.info(new String(msg.getBody()));
}catch(Exception e){
e.printStackTrace();
}
}
}

浙公网安备 33010602011771号