生活随笔
收集整理的這篇文章主要介紹了
Spring整合ActiveMQ接收消息
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
操作步驟
第一步:把Activemq相關的jar包,添加到工程中
第二步:創建一個MessageListener的實現類,負責監聽
第三步:配置MessageListener監聽器
第四步:初始化Spring容器,進行監聽
添加jar包
<dependency><groupId>org.apache.activemq
</groupId><artifactId>activemq-all
</artifactId>
</dependency>
創建監聽器
創建MessageListener對象
用于接收消息
public class MyMessageListener implements MessageListener {@Overridepublic void onMessage(Message message) {
try {TextMessage textMessage = (TextMessage) message;String text = textMessage.getText();System.out.println(text);}
catch (Exception e) {e.printStackTrace();}}}
配置監聽器
配置MessageListener
添加配置文件
applicationContext-activemq.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsdhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsdhttp://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.2.xsd"><bean id="targetConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory"><constructor-arg name="brokerURL" value="tcp://192.168.25.168:61616"/></bean><bean id="connectionFactory" class="org.springframework.jms.connection.SingleConnectionFactory"><property name="targetConnectionFactory" ref="targetConnectionFactory"></property></bean><bean id="test-queue" class="org.apache.activemq.command.ActiveMQQueue"><constructor-arg name="name" value="test-queue"></constructor-arg></bean><bean id="itemAddTopic" class="org.apache.activemq.command.ActiveMQTopic"><constructor-arg name="name" value="item-add-topic"></constructor-arg></bean><bean id="myMessageListener" class="com.taotao.search.listener.MyMessageListener"/><bean class="org.springframework.jms.listener.DefaultMessageListenerContainer"><property name="connectionFactory" ref="connectionFactory" /><property name="destination" ref="test-queue" /><property name="messageListener" ref="myMessageListener" /></bean>
</beans>
加載配置文件
初始化Spring容器
進行監聽
public class TestSpringActiveMq {@Test
public void testSpringActiveMq() throws Exception {ApplicationContext applicationContext =
new ClassPathXmlApplicationContext(
"classpath:spring/applicationContext-activemq.xml");System.
in.read();}
}
總結
以上是生活随笔為你收集整理的Spring整合ActiveMQ接收消息的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。