ActiveMQ結(jié)合Spring收發(fā)消息的示例代碼
ActiveMQ 結(jié)合 Spring 收發(fā)消息
直接使用 ActiveMQ 的方式需要重復(fù)寫(xiě)很多代碼,且不利于管理,Spring 提供了一種更加簡(jiǎn)便的方式————Spring JMS ,通過(guò)它可以更加方便地使用 ActiveMQ。
Maven 依賴(lài)
結(jié)合Spring使用ActiveMQ的依賴(lài)如下:
<!-- Spring JMS -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jms</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- xbean 如<amq:connectionFactory /> -->
<dependency>
<groupId>org.apache.xbean</groupId>
<artifactId>xbean-spring</artifactId>
<version>3.16</version>
</dependency>
<!-- ActiiveMQ -->
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-core</artifactId>
<version>5.7.0</version>
</dependency>
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-pool</artifactId>
<version>5.7.0</version>
</dependency>
ActiveMQ.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:amq="http://activemq.apache.org/schema/core"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://activemq.apache.org/schema/core
http://activemq.apache.org/schema/core/activemq-core-5.12.1.xsd">
<!-- ActiveMQ 連接工廠(chǎng) -->
<amq:connectionFactory id="amqConnectionFactory"
brokerURL="tcp://localhost:61616"
userName="admin"
password="admin" />
<!-- 提高效率,配置JMS連接工廠(chǎng) -->
<bean id="connectionFactory" class="org.springframework.jms.connection.CachingConnectionFactory">
<constructor-arg ref="amqConnectionFactory" />
<property name="sessionCacheSize" value="100" />
</bean>
<!-- 定義消息隊(duì)列(Queue)-->
<!-- <bean id="QueueDestination" class="org.apache.activemq.command.ActiveMQQueue">
<!– 設(shè)置消息隊(duì)列的名字 –>
<constructor-arg value="Queue-zy"/>
</bean>-->
<!--定義主題(Topic)-->
<bean id="topicDestination" class="org.apache.activemq.command.ActiveMQTopic">
<constructor-arg value="Topic-zy"/>
</bean>
<!-- 配置JMS模板(Queue),Spring提供的JMS工具類(lèi),利用它發(fā)送、接收消息。 -->
<bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
<property name="connectionFactory" ref="connectionFactory" />
<property name="defaultDestination" ref="topicDestination" />
<property name="receiveTimeout" value="10000" />
<!-- true是topic,false是queue,默認(rèn)是false -->
<property name="pubSubDomain" value="true" />
</bean>
<!-- 配置消息隊(duì)列監(jiān)聽(tīng)者(Queue or Topic) -->
<bean id="messageListener" class="com.service.TopicMessageListener" />
<!-- 顯示注入消息監(jiān)聽(tīng)容器,配置連接工廠(chǎng),監(jiān)聽(tīng)的目標(biāo)是QueueDestination,監(jiān)聽(tīng)器是上面定義的監(jiān)聽(tīng)器 -->
<bean id="ListenerContainer"
class="org.springframework.jms.listener.DefaultMessageListenerContainer">
<property name="connectionFactory" ref="connectionFactory" />
<property name="destination" ref="topicDestination" />
<property name="messageListener" ref="messageListener" />
</bean>
</beans>
配置 connectionFactory
connectionFactory 是 Spring 用于創(chuàng)建到 JMS 服務(wù)器鏈接的,Spring 提供了多種 connectionFactory。
<!-- ActiveMQ 連接工廠(chǎng) -->
<amq:connectionFactory id="amqConnectionFactory"
brokerURL="tcp://localhost:61616"
userName="admin"
password="admin" />
<!-- 提高效率,配置JMS連接工廠(chǎng) -->
<bean id="connectionFactory" class="org.springframework.jms.connection.CachingConnectionFactory">
<constructor-arg ref="amqConnectionFactory" />
<property name="sessionCacheSize" value="100" />
</bean>
配置Queue
<bean id="QueueDestination" class="org.apache.activemq.command.ActiveMQQueue">
<!-- 設(shè)置消息隊(duì)列的名字 -->
<constructor-arg value="Queue-zy"/>
</bean>
配置Topic
<bean id="topicDestination" class="org.apache.activemq.command.ActiveMQTopic">
<constructor-arg value="Topic-zy"/>
</bean>
配置JMS消息模板——jmsTemplate
<!-- 配置JMS模板,Spring提供的JMS工具類(lèi),利用它發(fā)送、接收消息--> <bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate"> <property name="connectionFactory" ref="connectionFactory" /> <property name="defaultDestination" ref="QueueDestination" /> <!--<property name="defaultDestination" ref="topicDestination" />--> <property name="receiveTimeout" value="10000" /> <property name="pubSubDomain" value="false" /><!-- true是topic,false是queue,默認(rèn)是false --> </bean>
最后,在 applicationContext.xml 中引入配置好的 ActiveMQ.xml
<import resource="ActiveMQ.xml" />
以上就是配置文件相關(guān)的,下面是具體的業(yè)務(wù)代碼。
消息生產(chǎn)者服務(wù)
@Service
public class ProducerService {
@Autowired
private JmsTemplate jmsTemplate;
//使用默認(rèn)目的地
public void sendMessageDefault(final String msg){
Destination destination = jmsTemplate.getDefaultDestination();
System.out.println("向隊(duì)列: " + destination + " 成功發(fā)送一條消息");
jmsTemplate.send(new MessageCreator() {
public Message createMessage(Session session) throws JMSException {
return session.createTextMessage(msg);
}
});
}
//可指定目的地
public void sendMessage(Destination destination,final String msg){
jmsTemplate.send(destination, new MessageCreator() {
public Message createMessage(Session session) throws JMSException {
return session.createTextMessage(msg);
}
});
}
}
消息消費(fèi)者服務(wù)
@Service
public class ConsumerService {
@Autowired
private JmsTemplate jmsTemplate;
//從指定的Destination接收消息
public TextMessage recive(Destination destination){
TextMessage message = (TextMessage) jmsTemplate.receive(destination);
try {
System.out.println("從隊(duì)列" + destination.toString() + "收到了消息" + message.getText());
} catch (JMSException e) {
e.printStackTrace();
}
return message;
}
//從默認(rèn)的Destination接收消息
public void reciveDefault(){
Destination destination = jmsTemplate.getDefaultDestination();
jmsTemplate.setReceiveTimeout(5000);
while(true){
TextMessage message = (TextMessage) jmsTemplate.receive(destination);
try {
//這里還是同一個(gè)消費(fèi)者
System.out.println("消費(fèi)者 從目的地 " + destination.toString() + " 收到了消息" + message.getText());
} catch (JMSException e) {
e.printStackTrace();
}
}
}
}
生產(chǎn)者
直接在 main 方法中獲取 ApplicationContext 運(yùn)行,便于測(cè)試。
@Component
public class MsgProducer {
@Autowired
private ProducerService producerService;
public void send(){
System.out.println("生產(chǎn)者開(kāi)始發(fā)送消息:");
for(int i = 1; i < 11; i++){
String msg = "生產(chǎn)者發(fā)出的消息";
producerService.sendMessageDefault(msg + "-----" + i);
}
}
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:/applicationContext.xml");
MsgProducer msgProducer = context.getBean(MsgProducer.class);
msgProducer.send();
}
}
消費(fèi)者
@Component
public class MsgConsumer {
@Autowired
private ConsumerService consumerService;
public void recive(){
System.out.println("消費(fèi)者 1 開(kāi)始接收消息:");
consumerService.reciveDefault();
}
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:/applicationContext.xml");
MsgConsumer msgConsumer = context.getBean(MsgConsumer.class);
msgConsumer.recive();
}
}
接下來(lái)就可以啟動(dòng)項(xiàng)目。同樣是使用兩種方式測(cè)試。
第一種方式————點(diǎn)對(duì)點(diǎn)(Queue)
同步的方式
先啟動(dòng)生產(chǎn)者發(fā)送10條消息, 再啟動(dòng)消費(fèi)者,可以看到控制臺(tái)顯示成功收到10條消息。


異步監(jiān)聽(tīng)的方式
通過(guò)監(jiān)聽(tīng)器即可實(shí)現(xiàn)異步接收消息的效果,而不是像上面使用 while() 輪詢(xún)同步的方式。
項(xiàng)目中一般都是使用異步監(jiān)聽(tīng)的方式,在 A 服務(wù)中發(fā)送了一條消息,B 服務(wù)可以利用消息監(jiān)聽(tīng)器監(jiān)聽(tīng),當(dāng)收到消息后,進(jìn)行相應(yīng)的操作。
消息監(jiān)聽(tīng)器(3種)
通過(guò)繼承 JMS 中的 MessageListener 接口,實(shí)現(xiàn) onMessage() 方法,就可以自定義監(jiān)聽(tīng)器。這是最基本的監(jiān)聽(tīng)器。(可根據(jù)業(yè)務(wù)實(shí)現(xiàn)自定義的功能)
另外spring也給我們提供了其他類(lèi)型的消息監(jiān)聽(tīng)器,比如 SessionAwareMessageListener,它的作用不僅可以接收消息,還可以發(fā)送一條消息通知對(duì)方表示自己收到了消息。(還有一種是 MessageListenerAdapter)
一個(gè)簡(jiǎn)單的自定義監(jiān)聽(tīng)器如下:收到消息后打印消息
public class QueueMessageListener implements MessageListener {
public void onMessage(Message message) {
//如果有消息
TextMessage tmessage = (TextMessage) message;
try {
if(tmessage != null){
System.out.println("監(jiān)聽(tīng)器監(jiān)聽(tīng)消息:"+tmessage.getText());
}
} catch (JMSException e) {
e.printStackTrace();
}
}
}
在 ActiveMQ.xml 中引入消息監(jiān)聽(tīng)器:
<!-- 配置消息隊(duì)列監(jiān)聽(tīng)者(Queue) -->
<bean id="queueMessageListener" class="com.service.QueueMessageListener" />
<!-- 顯示注入消息監(jiān)聽(tīng)容器,配置連接工廠(chǎng),監(jiān)聽(tīng)的目標(biāo)是QueueDestination 或 topicDestination,監(jiān)聽(tīng)器是上面自定義的監(jiān)聽(tīng)器 -->
<bean id="queueListenerContainer"
class="org.springframework.jms.listener.DefaultMessageListenerContainer">
<property name="connectionFactory" ref="connectionFactory" />
<property name="destination" ref="QueueDestination" />
<!--<property name="destination" ref="topicDestination" />-->
<property name="messageListener" ref="queueMessageListener" />
</bean>
可以看到,當(dāng)使用消息監(jiān)聽(tīng)器之后,每發(fā)送一條消息立馬就會(huì)被監(jiān)聽(tīng)到:

第二種方式————發(fā)布/訂閱(Topic)
同步的方式
類(lèi)似點(diǎn)對(duì)點(diǎn)中同步的方式,只是每個(gè)消費(fèi)者都能收到生產(chǎn)者發(fā)出的全部消息,不再贅述。
異步監(jiān)聽(tīng)的方式
啟動(dòng)兩個(gè)監(jiān)聽(tīng)器(兩個(gè)消費(fèi)者),對(duì)消息進(jìn)行異步監(jiān)聽(tīng)??词欠窀髯阅苁盏缴a(chǎn)者發(fā)送的消息。
<!-- 配置兩個(gè)監(jiān)聽(tīng)器 --> <bean id="messageListener" class="com.service.TopicMessageListener" /> <bean id="messageListener2" class="com.service.TopicMessageListener2" />

可以看到,每個(gè)監(jiān)聽(tīng)器各自都收到了生產(chǎn)者發(fā)送的10條消息。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
IDEA 2020.1 搜索不到Chinese (Simplified) Language
小編在安裝中文插件時(shí)遇到IDEA 2020.1 搜索不到Chinese ​(Simplified)​ Language Pack EAP,無(wú)法安裝的問(wèn)題,本文給大家分享我的解決方法,感興趣的朋友一起看看吧2020-04-04
AJAX中Get請(qǐng)求報(bào)錯(cuò)404的原因以及解決辦法
剛學(xué)習(xí)一門(mén)技術(shù)時(shí)總會(huì)踩一些坑,下面這篇文章主要給大家介紹了關(guān)于AJAX中Get請(qǐng)求報(bào)錯(cuò)404的原因及解決辦法的相關(guān)資料,文中通過(guò)實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2023-03-03
springboot項(xiàng)目接入天貓精靈語(yǔ)音功能
小編最近接手一個(gè)項(xiàng)目,涉及到天貓精靈的語(yǔ)音功能,今天小編通過(guò)本文給大家分享下springboot項(xiàng)目接入天貓精靈語(yǔ)音功能的詳細(xì)過(guò)程及實(shí)例代碼,感興趣的朋友跟隨小編一起看看吧2021-12-12
springboot使用單元測(cè)試實(shí)戰(zhàn)
這篇文章主要介紹了springboot使用單元測(cè)試實(shí)戰(zhàn),小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-09-09
剖析Java中阻塞隊(duì)列的實(shí)現(xiàn)原理及應(yīng)用場(chǎng)景
這篇文章主要介紹了剖析Java中阻塞隊(duì)列的實(shí)現(xiàn)原理及應(yīng)用場(chǎng)景,這里也對(duì)阻塞和非阻塞隊(duì)列的不同之處進(jìn)行了對(duì)比,需要的朋友可以參考下2015-12-12
Java應(yīng)用啟動(dòng)停止重啟Shell腳本模板server.sh
這篇文章主要為大家介紹了Java應(yīng)用啟動(dòng)、停止、重啟Shell腳本模板server.sh,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-08-08
手把手帶你理解java線(xiàn)程池之工作隊(duì)列workQueue
這篇文章主要介紹了java線(xiàn)程池之工作隊(duì)列workQueue,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-09-09

