1,添加依賴spring
<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 json
//rabbitmq-config.properties mq.host=127.0.0.1 mq.username=admin mq.password=admin mq.port=5672 mq.vhost=/
3,建立配置文件 application-mq.xmlapp
<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中引入ide
<import resource="classpath*:application-mq.xml" />
5,建立監聽spa
@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(); } } }