ActiveMQ学习笔记(5)——使用Spring JMS收发消息

本文详细介绍了使用Spring JMS进行队列和主题消息的收发操作,包括配置、代码实现和测试流程,展示了如何利用Spring简化消息处理过程。

  ActiveMQ学习笔记(四)http://my.oschina.net/xiaoxishan/blog/380446 中记录了如何使用原生的方式从ActiveMQ中收发消息。可以看出,每次收发消息都要写许多重复的代码,Spring 为我们提供了更为方便的方式,这就是Spring JMS。我们通过一个例子展开讲述。包括队列、主题消息的收发相关的Spring配置、代码、测试。

       本例中,消息的收发都写在了一个工程里。

1.使用maven管理依赖包

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
< dependencies >
     < dependency >
         < groupId >junit</ groupId >
         < artifactId >junit</ artifactId >
         < version >4.12</ version >
         < scope >test</ scope >
     </ dependency >
     < dependency >
         < groupId >org.apache.activemq</ groupId >
         < artifactId >activemq-all</ artifactId >
         < version >5.11.0</ version >
     </ dependency >
     < dependency >
         < groupId >org.springframework</ groupId >
         < artifactId >spring-jms</ artifactId >
         < version >4.1.4.RELEASE</ version >
     </ dependency >
     < dependency >  
         < groupId >org.springframework</ groupId >  
         < artifactId >spring-test</ artifactId >  
         < version >4.1.4.RELEASE</ version >  
     </ dependency
</ dependencies >


2.队列消息的收发

2.1Spring配置文件
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<? xml  version = "1.0"  encoding = "UTF-8" ?>
< beans  xmlns = "http://www.springframework.org/schema/beans"
     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.xsd">
 
     <!-- 配置JMS连接工厂 -->
     < bean  id = "connectionFactory"  class = "org.apache.activemq.ActiveMQConnectionFactory" >
         < property  name = "brokerURL"  value = "failover:(tcp://localhost:61616)"  />
     </ bean >
     
     <!-- 定义消息队列(Queue) -->
     < bean  id = "queueDestination"  class = "org.apache.activemq.command.ActiveMQQueue" >
         <!-- 设置消息队列的名字 -->
         < constructor-arg >
             < value >queue1</ value >
         </ constructor-arg >
     </ bean >
     
     <!-- 配置JMS模板(Queue),Spring提供的JMS工具类,它发送、接收消息。 -->
     < bean  id = "jmsTemplate"  class = "org.springframework.jms.core.JmsTemplate" >
         < property  name = "connectionFactory"  ref = "connectionFactory"  />
         < property  name = "defaultDestination"  ref = "queueDestination"  />
         < property  name = "receiveTimeout"  value = "10000"  />
     </ bean >
     
     <!--queue消息生产者 -->
     < bean  id = "producerService"  class = "guo.examples.mq02.queue.ProducerServiceImpl" >
         < property  name = "jmsTemplate"  ref = "jmsTemplate" ></ property >
     </ bean >
 
     <!--queue消息消费者 -->
     < bean  id = "consumerService"  class = "guo.examples.mq02.queue.ConsumerServiceImpl" >
         < property  name = "jmsTemplate"  ref = "jmsTemplate" ></ property >
     </ bean >


2.2消息生产者代码

从下面的代码可以出,使用Spring JMS,可以减少重复代码(接口类ProducerService代码省略)。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package  guo.examples.mq02.queue;
 
import  javax.jms.Destination;
import  javax.jms.JMSException;
import  javax.jms.Message;
import  javax.jms.Session;
 
import  org.springframework.jms.core.JmsTemplate;
import  org.springframework.jms.core.MessageCreator;
 
public  class  ProducerServiceImpl  implements  ProducerService {
 
   private  JmsTemplate jmsTemplate;
   
   /**
    * 向指定队列发送消息
    */
   public  void  sendMessage(Destination destination,  final  String msg) {
     System.out.println( "向队列"  + destination.toString() +  "发送了消息------------"  + msg);
     jmsTemplate.send(destination,  new  MessageCreator() {
       public  Message createMessage(Session session)  throws  JMSException {
         return  session.createTextMessage(msg);
       }
     });
   }
 
/**
  * 向默认队列发送消息
  */
   public  void  sendMessage( final  String msg) {
     String destination =  jmsTemplate.getDefaultDestination().toString();
     System.out.println( "向队列"  +destination+  "发送了消息------------"  + msg);
     jmsTemplate.send( new  MessageCreator() {
       public  Message createMessage(Session session)  throws  JMSException {
         return  session.createTextMessage(msg);
       }
     });
 
   }
 
   public  void  setJmsTemplate(JmsTemplate jmsTemplate) {
     this .jmsTemplate = jmsTemplate;
   }
 
}
2.3消息消费者代码
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package  guo.examples.mq02.queue;
 
import  javax.jms.Destination;
import  javax.jms.JMSException;
import  javax.jms.TextMessage;
 
import  org.springframework.jms.core.JmsTemplate;
 
public  class  ConsumerServiceImpl  implements  ConsumerService {
 
     private  JmsTemplate jmsTemplate;
 
     /**
      * 接受消息
      */
     public  void  receive(Destination destination) {
         TextMessage tm = (TextMessage) jmsTemplate.receive(destination);
         try  {
             System.out.println( "从队列"  + destination.toString() +  "收到了消息:\t"
                     + tm.getText());
         catch  (JMSException e) {
             e.printStackTrace();
         }
     }
 
     public  void  setJmsTemplate(JmsTemplate jmsTemplate) {
         this .jmsTemplate = jmsTemplate;
     }
 
}


2.4队列消息监听

接受消息的时候,可以不用2.3节中的方式,Spring JMS同样提供了消息监听的模式,下面给出对应的配置和代码。

Spring配置

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<!-- 定义消息队列(Queue),我们监听一个新的队列,queue2 -->
     < bean  id = "queueDestination2"  class = "org.apache.activemq.command.ActiveMQQueue" >
         <!-- 设置消息队列的名字 -->
         < constructor-arg >
             < value >queue2</ value >
         </ constructor-arg >
     </ bean >
     
     <!-- 配置消息队列监听者(Queue),代码下面给出,只有一个onMessage方法 -->
     < bean  id = "queueMessageListener"  class = "guo.examples.mq02.queue.QueueMessageListener"  />
     
     <!-- 消息监听容器(Queue),配置连接工厂,监听的队列是queue2,监听器是上面定义的监听器 -->
     < bean  id = "jmsContainer"
         class = "org.springframework.jms.listener.DefaultMessageListenerContainer" >
         < property  name = "connectionFactory"  ref = "connectionFactory"  />
         < property  name = "destination"  ref = "queueDestination2"  />
         < property  name = "messageListener"  ref = "queueMessageListener"  />
     </ bean >

监听类代码

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package  guo.examples.mq02.queue;
 
import  javax.jms.JMSException;
import  javax.jms.Message;
import  javax.jms.MessageListener;
import  javax.jms.TextMessage;
 
public  class  QueueMessageListener  implements  MessageListener {
         //当收到消息时,自动调用该方法。
     public  void  onMessage(Message message) {
         TextMessage tm = (TextMessage) message;
         try  {
             System.out.println( "ConsumerMessageListener收到了文本消息:\t"
                     + tm.getText());
         catch  (JMSException e) {
             e.printStackTrace();
         }
     }
 
}



3.主题消息收发

     在使用Spring JMS的时候,主题(Topic)和队列消息的主要差异体现在JmsTemplate中"pubSubDomain"是否设置为True。如果为True,则是Topic;如果是false或者默认,则是queue。

?
1
< property  name = "pubSubDomain"  value = "true"  />


3.1Spring配置
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<!-- 定义消息主题(Topic) -->
     < bean  id = "topicDestination"  class = "org.apache.activemq.command.ActiveMQTopic" >
         < constructor-arg >
             < value >guo_topic</ value >
         </ constructor-arg >
     </ bean >
     <!-- 配置JMS模板(Topic),pubSubDomain="true"-->
     < bean  id = "topicJmsTemplate"  class = "org.springframework.jms.core.JmsTemplate" >
         < property  name = "connectionFactory"  ref = "connectionFactory"  />
         < property  name = "defaultDestination"  ref = "topicDestination"  />
         < property  name = "pubSubDomain"  value = "true"  />
         < property  name = "receiveTimeout"  value = "10000"  />
     </ bean >
     <!--topic消息发布者 -->
     < bean  id = "topicProvider"  class = "guo.examples.mq02.topic.TopicProvider" >
         < property  name = "topicJmsTemplate"  ref = "topicJmsTemplate" ></ property >
     </ bean >
     <!-- 消息主题监听者 和 主题监听容器 可以配置多个,即多个订阅者 -->
     <!-- 消息主题监听者(Topic) -->
     < bean  id = "topicMessageListener"  class = "guo.examples.mq02.topic.TopicMessageListener"  />
     <!-- 主题监听容器 (Topic) -->
     < bean  id = "topicJmsContainer"
         class = "org.springframework.jms.listener.DefaultMessageListenerContainer" >
         < property  name = "connectionFactory"  ref = "connectionFactory"  />
         < property  name = "destination"  ref = "topicDestination"  />
         < property  name = "messageListener"  ref = "topicMessageListener"  />
     </ bean >
3.2消息发布者
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package  guo.examples.mq02.topic;
 
import  javax.jms.Destination;
import  javax.jms.JMSException;
import  javax.jms.Message;
import  javax.jms.Session;
 
import  org.springframework.jms.core.JmsTemplate;
import  org.springframework.jms.core.MessageCreator;
 
public  class  TopicProvider {
 
     private  JmsTemplate topicJmsTemplate;
 
     /**
      * 向指定的topic发布消息
     
      * @param topic
      * @param msg
      */
     public  void  publish( final  Destination topic,  final  String msg) {
 
         topicJmsTemplate.send(topic,  new  MessageCreator() {
             public  Message createMessage(Session session)  throws  JMSException {
                 System.out.println( "topic name 是"  + topic.toString()
                         ",发布消息内容为:\t"  + msg);
                 return  session.createTextMessage(msg);
             }
         });
     }
 
     public  void  setTopicJmsTemplate(JmsTemplate topicJmsTemplate) {
         this .topicJmsTemplate = topicJmsTemplate;
     }
 
}
3.3消息订阅者(监听)
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package  guo.examples.mq02.topic;
 
import  javax.jms.JMSException;
import  javax.jms.Message;
import  javax.jms.MessageListener;
import  javax.jms.TextMessage;
/**
  *和队列监听的代码一样。
  */
public  class  TopicMessageListener  implements  MessageListener {
 
     public  void  onMessage(Message message) {
         TextMessage tm = (TextMessage) message;
         try  {
             System.out.println( "TopicMessageListener \t"  + tm.getText());
         catch  (JMSException e) {
             e.printStackTrace();
         }
     }
 
}


4.测试

4.1 测试代码
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
package  guo.examples.mq02;
 
import  javax.jms.Destination;
 
import  guo.examples.mq02.queue.ConsumerService;
import  guo.examples.mq02.queue.ProducerService;
import  guo.examples.mq02.topic.TopicProvider;
 
import  org.junit.Test;
import  org.junit.runner.RunWith;
import  org.springframework.beans.factory.annotation.Autowired;
import  org.springframework.beans.factory.annotation.Qualifier;
import  org.springframework.test.context.ContextConfiguration;
import  org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
 
/**
  * 测试Spring JMS
 
  * 1.测试生产者发送消息
 
  * 2. 测试消费者接受消息
 
  * 3. 测试消息监听
 
  * 4.测试主题监听
  *
  */
@RunWith (SpringJUnit4ClassRunner. class )
// ApplicationContext context = new
// ClassPathXmlApplicationContext("applicationContext.xml");
@ContextConfiguration ( "/applicationContext.xml" )
public  class  SpringJmsTest {
 
     /**
      * 队列名queue1
      */
     @Autowired
     private  Destination queueDestination;
 
     /**
      * 队列名queue2
      */
     @Autowired
     private  Destination queueDestination2;
 
     /**
      * 主题 guo_topic
      */
     @Autowired
     @Qualifier ( "topicDestination" )
     private  Destination topic;
 
     /**
      * 主题消息发布者
      */
     @Autowired
     private  TopicProvider topicProvider;
 
     /**
      * 队列消息生产者
      */
     @Autowired
     @Qualifier ( "producerService" )
     private  ProducerService producer;
 
     /**
      * 队列消息生产者
      */
     @Autowired
     @Qualifier ( "consumerService" )
     private  ConsumerService consumer;
 
     /**
      * 测试生产者向queue1发送消息
      */
     @Test
     public  void  testProduce() {
         String msg =  "Hello world!" ;
         producer.sendMessage(msg);
     }
 
     /**
      * 测试消费者从queue1接受消息
      */
     @Test
     public  void  testConsume() {
         consumer.receive(queueDestination);
     }
 
     /**
      * 测试消息监听
     
      * 1.生产者向队列queue2发送消息
     
      * 2.ConsumerMessageListener监听队列,并消费消息
      */
     @Test
     public  void  testSend() {
         producer.sendMessage(queueDestination2,  "Hello China~~~~~~~~~~~~~~~" );
     }
 
     /**
      * 测试主题监听
     
      * 1.生产者向主题发布消息
     
      * 2.ConsumerMessageListener监听主题,并消费消息
      */
     @Test
     public  void  testTopic()  throws  Exception {
         topicProvider.publish(topic,  "Hello T-To-Top-Topi-Topic!" );
     }
 
}
4.2 测试结果
?
1
2
3
4
5
6
topic name 是topic: //guo_topic ,发布消息内容为:    Hello T-To-Top-Topi-Topic!
TopicMessageListener   Hello T-To-Top-Topi-Topic!
向队列queue: //queue2 发送了消息------------Hello China~~~~~~~~~~~~~~~
ConsumerMessageListener收到了文本消息: Hello China~~~~~~~~~~~~~~~
向队列queue: //queue1 发送了消息------------Hello world!
从队列queue: //queue1 收到了消息: Hello world!

5.代码地址

http://pan.baidu.com/s/1gdvPpWf

代码转载自:https://pan.quark.cn/s/f87b8041184b Language: 中文 欢迎来到戈戈圈! 当你点开这个存储库的时候,你会看到戈戈圈的图标↓ 本图片均在知识共享 署名-相同方式共享 3.0(CC BY-SA 3.0)许可协议下提供,如有授权遵照授权协议使用。 那么恭喜你,当你看到这个图标的时候,就代表着你已经正式成为了一名戈团子啦! 欢迎你来到这个充满爱与希望的大家庭! 「与大家创造更多快乐,与人们一起改变世界。 」 戈戈圈是一个在中国海南省诞生的创作企划,由王戈wg的妹妹于2018年7月14日正式公开。 戈戈圈的创作类型广泛,囊括插画、小说、音乐等各种作品类型。 戈戈圈的目前成员: Contributors 此外,支持戈戈圈及本企划的成员被称为“戈团子”。 “戈团子”一词最初来源于2015年出生的名叫“团子”的大熊猫,也因为一种由糯米包裹着馅料蒸熟而成的食品也名为“团子”,不仅有团圆之意,也蕴涵着团结友爱的象征意义和大家的美好期盼,因此我们最终于2021年初决定命名戈戈圈的粉丝为“戈团子”。 如果你对戈戈圈有兴趣的话,欢迎加入我们吧(σ≧︎▽︎≦︎)σ! 由于王戈wg此前投稿的相关视频并未详细说明本企划的信息,且相关视频的表述极其模糊,我们特此创建这个存储库,以文字的形式向大家介绍戈戈圈。 戈戈圈自2018年7月14日成立至今,一直以来都秉持着包容开放、和谐友善的原则。 我们深知自己的责任和使命,始终尊重社会道德习俗,严格遵循国家法律法规,为维护社会稳定和公共利益做出了积极的贡献。 因此,我们不允许任何人或组织以“戈戈圈”的名义在网络平台或现实中发布不当言论,同时我们也坚决反对过度宣传戈戈圈的行为,包括但不限于与戈戈圈无关的任何...
内容概要:本文详细介绍了一个基于YOLOv8的血细胞智能检测系统全流程开发指南,涵盖从环境搭建、数据准备、模型训练与验证到UI交互系统开发的完整实践过程。项目利用YOLOv8高精度、高速度的优势,实现对白细胞、红细胞和血小板的自动识别与分类,准确率超过93%,单张图像检测仅需0.3秒。通过公开或自建血细胞数据集,结合LabelImg标注工具和Streamlit开发可视化界面,构建了具备图像上传、实时检测、结果统计与异常提示功能的智能系统,并提供了论文撰写与成果展示建议,强化其在医疗场景中的应用价值。; 适合人群:具备一定Python编程与深度学习基础,从事计算机视觉、医疗AI相关研究或项目开发的高校学生、科研人员及工程技术人员,尤其适合需要完成毕业设计或医疗智能化项目实践的开发者。; 使用场景及目标:①应用于医院或检验机构辅助医生进行血涂片快速筛查,提升检测效率与一致性;②作为深度学习在医疗影像领域落地的教学案例,掌握YOLOv8在实际项目中的训练、优化与部署流程;③用于学术论文写作与项目成果展示,理解技术与临床需求的结合方式。; 阅读建议:建议按照“数据→模型→系统→应用”顺序逐步实践,重点理解数据标注规范、模型参数设置与UI集成逻辑,同时结合临床需求不断优化系统功能,如增加报告导出、多类别细粒度分类等扩展模块。
基于蒙特卡洛,copula函数,fuzzy-kmeans获取6个典型场景进行随机优化多类型电动汽车采用分时电价调度,考虑上级电网出力、峰谷差惩罚费用、风光调度、电动汽车负荷调度费用和网损费用内容概要:本文围绕多类型电动汽车在分时电价机制下的优化调度展开研究,采用蒙特卡洛模拟、Copula函数和模糊K-means聚类方法获取6个典型场景,并在此基础上进行随机优化。模型综合考虑了上级电网出力、峰谷差惩罚费用、风光可再生能源调度、电动汽车负荷调度成本以及电网网损费用等多个关键因素,旨在实现电力系统运行的经济性与稳定性。通过Matlab代码实现相关算法,验证所提方法的有效性与实用性。; 适合人群:具备一定电力系统基础知识和Matlab编程能力的研究生、科研人员及从事新能源、智能电网、电动汽车调度相关工作的工程技术人员。; 使用场景及目标:①用于研究大规模电动汽车接入电网后的负荷调控策略;②支持含风光等可再生能源的综合能源系统优化调度;③为制定合理的分时电价政策及降低电网峰谷差提供技术支撑;④适用于学术研究、论文复现与实际项目仿真验证。; 阅读建议:建议读者结合文中涉及的概率建模、聚类分析与优化算法部分,动手运行并调试Matlab代码,深入理解场景生成与随机优化的实现流程,同时可扩展至更多元化的应用场景如V2G、储能协同调度等。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值