Spring整合JMS——基于ActiveMQ实现

系统 1759 0

1.1       JMS 简介

       JMS 的全称是 Java Message Service ,即 Java 消息服务。它主要用于在生产者和消费者之间进行消息传递,生产者负责产生消息,而消费者负责接收消息。把它应用到实际的业务需求中的话我们可以在特定的时候利用生产者生成一消息,并进行发送,对应的消费者在接收到对应的消息后去完成对应的业务逻辑。对于消息的传递有两种类型,一种是点对点的,即一个生产者和一个消费者一一对应;另一种是发布 / 订阅模式,即一个生产者产生消息并进行发送后,可以由多个消费者进行接收。

1.2       Spring 整合 JMS

        JMS 做了一个简要介绍之后,接下来就讲一下 Spring 整合 JMS 的具体过程。 JMS 只是一个标准,真正在使用它的时候我们需要有它的具体实现,这里我们就使用 Apache activeMQ 来作为它的实现。所使用的依赖利用 Maven 来进行管理,具体依赖如下:

 

Xml代码   收藏代码
  1. < dependencies >   
  2.          < dependency >   
  3.              < groupId > junit </ groupId >   
  4.              < artifactId > junit </ artifactId >   
  5.              < version > 4.10 </ version >   
  6.              < scope > test </ scope >   
  7.          </ dependency >   
  8.          < dependency >   
  9.              < groupId > org.springframework </ groupId >   
  10.              < artifactId > spring-context </ artifactId >   
  11.              < version > ${spring-version} </ version >   
  12.          </ dependency >   
  13.          < dependency >   
  14.              < groupId > org.springframework </ groupId >   
  15.              < artifactId > spring-jms </ artifactId >   
  16.              < version > ${spring-version} </ version >   
  17.          </ dependency >   
  18.          < dependency >   
  19.              < groupId > org.springframework </ groupId >   
  20.              < artifactId > spring-test </ artifactId >   
  21.              < version > ${spring-version} </ version >   
  22.          </ dependency >   
  23.          < dependency >   
  24.              < groupId > javax.annotation </ groupId >   
  25.              < artifactId > jsr250-api </ artifactId >   
  26.              < version > 1.0 </ version >   
  27.          </ dependency >   
  28.          < dependency >   
  29.              < groupId > org.apache.activemq </ groupId >   
  30.              < artifactId > activemq-core </ artifactId >   
  31.              < version > 5.7.0 </ version >   
  32.          </ dependency >   
  33. </ dependencies >   

 

1.2.1  activeMQ准备

        既然是使用的 apache activeMQ 作为 JMS 的实现,那么首先我们应该到 apache 官网上下载 activeMQ http://activemq.apache.org/download.html ),进行解压后运行其 bin 目录下面的 activemq.bat 文件启动 activeMQ

1.2.2配置ConnectionFactory

       ConnectionFactory 是用于产生到 JMS 服务器的链接的, Spring 为我们提供了多个 ConnectionFactory ,有 SingleConnectionFactory CachingConnectionFactory SingleConnectionFactory 对于建立 JMS 服务器链接的请求会一直返回同一个链接,并且会忽略 Connection close 方法调用。 CachingConnectionFactory 继承了 SingleConnectionFactory ,所以它拥有 SingleConnectionFactory 的所有功能,同时它还新增了缓存功能,它可以缓存 Session MessageProducer MessageConsumer 。这里我们使用 SingleConnectionFactory 来作为示例。

Xml代码   收藏代码
  1. < bean   id = "connectionFactory"   class = "org.springframework.jms.connection.SingleConnectionFactory" />   

 

        这样就定义好产生 JMS 服务器链接的 ConnectionFactory 了吗?答案是非也。 Spring 提供的 ConnectionFactory 只是 Spring 用于管理 ConnectionFactory 的,真正产生到 JMS 服务器链接的 ConnectionFactory 还得是由 JMS 服务厂商提供,并且需要把它注入到 Spring 提供的 ConnectionFactory 中。我们这里使用的是 ActiveMQ 实现的 JMS ,所以在我们这里真正的可以产生 Connection 的就应该是由 ActiveMQ 提供的 ConnectionFactory 。所以定义一个 ConnectionFactory 的完整代码应该如下所示:

Xml代码   收藏代码
  1. <!-- 真正可以产生Connection的ConnectionFactory,由对应的 JMS服务厂商提供-->   
  2. < bean   id = "targetConnectionFactory"   class = "org.apache.activemq.ActiveMQConnectionFactory" >   
  3.      < property   name = "brokerURL"   value = "tcp://localhost:61616" />   
  4. </ bean >   
  5.   
  6. <!-- Spring用于管理真正的ConnectionFactory的ConnectionFactory -->   
  7. < bean   id = "connectionFactory"   class = "org.springframework.jms.connection.SingleConnectionFactory" >   
  8.      <!-- 目标ConnectionFactory对应真实的可以产生JMS Connection的ConnectionFactory -->   
  9.      < property   name = "targetConnectionFactory"   ref = "targetConnectionFactory" />   
  10. </ bean >   

  

1.2.3配置生产者

配置好 ConnectionFactory 之后我们就需要配置生产者。生产者负责产生消息并发送到 JMS 服务器,这通常对应的是我们的一个业务逻辑服务实现类。但是我们的服务实现类是怎么进行消息的发送的呢?这通常是利用 Spring 为我们提供的 JmsTemplate 类来实现的,所以配置生产者其实最核心的就是配置进行消息发送的 JmsTemplate 。对于消息发送者而言,它在发送消息的时候要知道自己该往哪里发,为此,我们在定义 JmsTemplate 的时候需要往里面注入一个 Spring 提供的 ConnectionFactory 对象。

Xml代码   收藏代码
  1. <!-- Spring提供的JMS工具类,它可以进行消息发送、接收等 -->   
  2. < bean   id = "jmsTemplate"   class = "org.springframework.jms.core.JmsTemplate" >   
  3.      <!-- 这个connectionFactory对应的是我们定义的Spring提供的那个ConnectionFactory对象 -->   
  4.      < property   name = "connectionFactory"   ref = "connectionFactory" />   
  5. </ bean >   

 

        在真正利用 JmsTemplate 进行消息发送的时候,我们需要知道消息发送的目的地,即 destination 。在 Jms 中有一个用来表示目的地的 Destination 接口,它里面没有任何方法定义,只是用来做一个标识而已。当我们在使用 JmsTemplate 进行消息发送时没有指定 destination 的时候将使用默认的 Destination 。默认 Destination 可以通过在定义 jmsTemplate bean 对象时通过属性 defaultDestination defaultDestinationName 来进行注入, defaultDestinationName 对应的就是一个普通字符串。在 ActiveMQ 中实现了两种类型的 Destination ,一个是点对点的 ActiveMQQueue ,另一个就是支持订阅 / 发布模式的 ActiveMQTopic 。在定义这两种类型的 Destination 时我们都可以通过一个 name 属性来进行构造,如:

 

 

 

 

Xml代码   收藏代码
  1. <!--这个是队列目的地,点对点的-->   
  2. < bean   id = "queueDestination"   class = "org.apache.activemq.command.ActiveMQQueue" >   
  3.      < constructor-arg >   
  4.          < value > queue </ value >   
  5.      </ constructor-arg >   
  6. </ bean >   
  7. <!--这个是主题目的地,一对多的-->   
  8. < bean   id = "topicDestination"   class = "org.apache.activemq.command.ActiveMQTopic" >   
  9.      < constructor-arg   value = "topic" />   
  10. </ bean >   

 

 

 

        假设我们定义了一个 ProducerService ,里面有一个向 Destination 发送纯文本消息的方法 sendMessage ,那么我们的代码就大概是这个样子:

 

 

 

 

Java代码   收藏代码
  1. package  com.tiantian.springintejms.service.impl;  
  2.    
  3. import  javax.annotation.Resource;  
  4. import  javax.jms.Destination;  
  5. import  javax.jms.JMSException;  
  6. import  javax.jms.Message;  
  7. import  javax.jms.Session;  
  8.    
  9. import  org.springframework.jms.core.JmsTemplate;  
  10. import  org.springframework.jms.core.MessageCreator;  
  11. import  org.springframework.stereotype.Component;  
  12.    
  13. import  com.tiantian.springintejms.service.ProducerService;  
  14.    
  15. @Component   
  16. public   class  ProducerServiceImpl  implements  ProducerService {  
  17.    
  18.      private  JmsTemplate jmsTemplate;  
  19.       
  20.      public   void  sendMessage(Destination destination,  final  String message) {  
  21.         System.out.println( "---------------生产者发送消息-----------------" );  
  22.         System.out.println( "---------------生产者发了一个消息:"  + message);  
  23.         jmsTemplate.send(destination,  new  MessageCreator() {  
  24.              public  Message createMessage(Session session)  throws  JMSException {  
  25.                  return  session.createTextMessage(message);  
  26.             }  
  27.         });  
  28.     }   
  29.   
  30.      public  JmsTemplate getJmsTemplate() {  
  31.         returnjmsTemplate;  
  32.     }   
  33.   
  34.      @Resource   
  35.      public   void  setJmsTemplate(JmsTemplate jmsTemplate) {  
  36.          this .jmsTemplate = jmsTemplate;  
  37.     }  
  38.    
  39. }  

 

 

 

        我们可以看到在 sendMessage 方法体里面我们是通过 jmsTemplate 来发送消息到对应的 Destination 的。到此,我们生成一个简单的文本消息并把它发送到指定目的地 Destination 的生产者就配置好了。

1.2.4配置消费者

生产者往指定目的地 Destination 发送消息后,接下来就是消费者对指定目的地的消息进行消费了。那么消费者是如何知道有生产者发送消息到指定目的地 Destination 了呢?这是通过 Spring 为我们封装的消息监听容器 MessageListenerContainer 实现的,它负责接收信息,并把接收到的信息分发给真正的 MessageListener 进行处理。每个消费者对应每个目的地都需要有对应的 MessageListenerContainer 。对于消息监听容器而言,除了要知道监听哪个目的地之外,还需要知道到哪里去监听,也就是说它还需要知道去监听哪个 JMS 服务器,这是通过在配置 MessageConnectionFactory 的时候往里面注入一个 ConnectionFactory 来实现的。所以我们 在配置一个 MessageListenerContainer 的时候有三个属性必须指定,一个是表示从哪里监听的 ConnectionFactory ;一个是表示监听什么的 Destination ;一个是接收到消息以后进行消息处理的 MessageListener Spring 一共为我们提供了两种类型的 MessageListenerContainer SimpleMessageListenerContainer DefaultMessageListenerContainer

SimpleMessageListenerContainer 会在一开始的时候就创建一个会话 session 和消费者 Consumer ,并且会使用标准的 JMS MessageConsumer.setMessageListener() 方法注册监听器让 JMS 提供者调用监听器的回调函数。它不会动态的适应运行时需要和参与外部的事务管理。兼容性方面,它非常接近于独立的 JMS 规范,但一般不兼容 Java EE JMS 限制。

大多数情况下我们还是使用的 DefaultMessageListenerContainer ,跟 SimpleMessageListenerContainer 相比, DefaultMessageListenerContainer 会动态的适应运行时需要,并且能够参与外部的事务管理。它很好的平衡了对 JMS 提供者要求低、先进功能如事务参与和兼容 Java EE 环境。

定义处理消息的 MessageListener

        要定义处理消息的 MessageListener 我们只需要实现 JMS 规范中的 MessageListener 接口就可以了。 MessageListener 接口中只有一个方法 onMessage 方法,当接收到消息的时候会自动调用该方法。

 

 

 

 

Java代码   收藏代码
  1. package  com.tiantian.springintejms.listener;  
  2.    
  3. import  javax.jms.JMSException;  
  4. import  javax.jms.Message;  
  5. import  javax.jms.MessageListener;  
  6. import  javax.jms.TextMessage;  
  7.    
  8. public   class  ConsumerMessageListener  implements  MessageListener {  
  9.    
  10.      public   void  onMessage(Message message) {  
  11.          //这里我们知道生产者发送的就是一个纯文本消息,所以这里可以直接进行强制转换,或者直接把onMessage方法的参数改成Message的子类TextMessage   
  12.         TextMessage textMsg = (TextMessage) message;  
  13.         System.out.println( "接收到一个纯文本消息。" );  
  14.          try  {  
  15.             System.out.println( "消息内容是:"  + textMsg.getText());  
  16.         }  catch  (JMSException e) {  
  17.             e.printStackTrace();  
  18.         }  
  19.     }  
  20.    
  21. }  

 

  

 

        有了 MessageListener 之后我们就可以在 Spring 的配置文件中配置一个消息监听容器了。

Xml代码   收藏代码
  1. <!--这个是队列目的地-->   
  2. < bean   id = "queueDestination"   class = "org.apache.activemq.command.ActiveMQQueue" >   
  3.      < constructor-arg >   
  4.          < value > queue </ value >   
  5.      </ constructor-arg >   
  6. </ bean >   
  7. <!-- 消息监听器 -->   
  8. < bean   id = "consumerMessageListener"   class = "com.tiantian.springintejms.listener.ConsumerMessageListener" />       
  9.   
  10. <!-- 消息监听容器 -->   
  11. < bean   id = "jmsContainer"          class = "org.springframework.jms.listener.DefaultMessageListenerContainer" >   
  12.      < property   name = "connectionFactory"   ref = "connectionFactory"   />   
  13.      < property   name = "destination"   ref = "queueDestination"   />   
  14.      < property   name = "messageListener"   ref = "consumerMessageListener"   />   
  15. </ bean >   

 

 

        我们可以看到我们定义了一个名叫 queue ActiveMQQueue 目的地,我们的监听器就是监听了发送到这个目的地的消息。

        至此我们的生成者和消费者都配置完成了,这也就意味着我们的整合已经完成了。这个时候完整的 Spring 的配置文件应该是这样的:

Xml代码   收藏代码
  1. <? xml   version = "1.0"   encoding = "UTF-8" ?>   
  2. < beans   xmlns = "http://www.springframework.org/schema/beans"   
  3.      xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"   xmlns:context = "http://www.springframework.org/schema/context"   
  4.      xmlns:jms = "http://www.springframework.org/schema/jms"   
  5.      xsi:schemaLocation ="http://www.springframework.org/schema/beans  
  6.      http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
  7.      http://www.springframework.org/schema/context  
  8.      http://www.springframework.org/schema/context/spring-context-3.0.xsd  
  9.     http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
  10.     http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms-3.0.xsd" >   
  11.    
  12.      < context:component-scan   base-package = "com.tiantian"   />   
  13.    
  14.      <!-- Spring提供的JMS工具类,它可以进行消息发送、接收等 -->   
  15.      < bean   id = "jmsTemplate"   class = "org.springframework.jms.core.JmsTemplate" >   
  16.          <!-- 这个connectionFactory对应的是我们定义的Spring提供的那个ConnectionFactory对象 -->   
  17.          < property   name = "connectionFactory"   ref = "connectionFactory" />   
  18.      </ bean >   
  19.       
  20.      <!-- 真正可以产生Connection的ConnectionFactory,由对应的 JMS服务厂商提供-->   
  21.      < bean   id = "targetConnectionFactory"   class = "org.apache.activemq.ActiveMQConnectionFactory" >   
  22.          < property   name = "brokerURL"   value = "tcp://localhost:61616" />   
  23.      </ bean >   
  24.       
  25.      <!-- Spring用于管理真正的ConnectionFactory的ConnectionFactory -->   
  26.      < bean   id = "connectionFactory"   class = "org.springframework.jms.connection.SingleConnectionFactory" >   
  27.          <!-- 目标ConnectionFactory对应真实的可以产生JMS Connection的ConnectionFactory -->   
  28.          < property   name = "targetConnectionFactory"   ref = "targetConnectionFactory" />   
  29.      </ bean >   
  30.       
  31.      <!--这个是队列目的地-->   
  32.      < bean   id = "queueDestination"   class = "org.apache.activemq.command.ActiveMQQueue" >   
  33.          < constructor-arg >   
  34.              < value > queue </ value >   
  35.          </ constructor-arg >   
  36.      </ bean >   
  37.      <!-- 消息监听器 -->   
  38.      < bean   id = "consumerMessageListener"   class = "com.tiantian.springintejms.listener.ConsumerMessageListener" />   
  39.      <!-- 消息监听容器 -->   
  40.      < bean   id = "jmsContainer"   
  41.          class = "org.springframework.jms.listener.DefaultMessageListenerContainer" >   
  42.          < property   name = "connectionFactory"   ref = "connectionFactory"   />   
  43.          < property   name = "destination"   ref = "queueDestination"   />   
  44.          < property   name = "messageListener"   ref = "consumerMessageListener"   />   
  45.      </ bean >   
  46. </ beans >   

 

 

        接着我们来测试一下,看看我们的整合是否真的成功了,测试代码如下:

 

 

 

 

Java代码   收藏代码
  1. package  com.tiantian.springintejms.test;  
  2.    
  3. import  javax.jms.Destination;  
  4.    
  5. import  org.junit.Test;  
  6. import  org.junit.runner.RunWith;  
  7. import  org.springframework.beans.factory.annotation.Autowired;  
  8. import  org.springframework.beans.factory.annotation.Qualifier;  
  9. import  org.springframework.test.context.ContextConfiguration;  
  10. import  org.springframework.test.context.junit4.SpringJUnit4ClassRunner;  
  11. import  com.tiantian.springintejms.service.ProducerService;  
  12.    
  13. @RunWith (SpringJUnit4ClassRunner. class )  
  14. @ContextConfiguration ( "/applicationContext.xml" )  
  15. public   class  ProducerConsumerTest {  
  16.    
  17.      @Autowired   
  18.      private  ProducerService producerService;  
  19.      @Autowired   
  20.      @Qualifier ( "queueDestination" )  
  21.      private  Destination destination;  
  22.       
  23.      @Test   
  24.      public   void  testSend() {  
  25.          for  ( int  i= 0 ; i< 2 ; i++) {  
  26.             producerService.sendMessage(destination,  "你好,生产者!这是消息:"  + (i+ 1 ));  
  27.         }  
  28.     }  
  29.       
  30. }  

 

 

 

        在上面的测试代码中我们利用生产者发送了两个消息,正常来说,消费者应该可以接收到这两个消息。运行测试代码后控制台输出如下:

 
Spring整合JMS——基于ActiveMQ实现
 

        看,控制台已经进行了正确的输出,这说明我们的整合确实是已经成功了。

Spring整合JMS——基于ActiveMQ实现


更多文章、技术交流、商务合作、联系博主

微信扫码或搜索:z360901061

微信扫一扫加我为好友

QQ号联系: 360901061

您的支持是博主写作最大的动力,如果您喜欢我的文章,感觉我的文章对您有帮助,请用微信扫描下面二维码支持博主2元、5元、10元、20元等您想捐的金额吧,狠狠点击下面给点支持吧,站长非常感激您!手机微信长按不能支付解决办法:请将微信支付二维码保存到相册,切换到微信,然后点击微信右上角扫一扫功能,选择支付二维码完成支付。

【本文对您有帮助就好】

您的支持是博主写作最大的动力,如果您喜欢我的文章,感觉我的文章对您有帮助,请用微信扫描上面二维码支持博主2元、5元、10元、自定义金额等您想捐的金额吧,站长会非常 感谢您的哦!!!

发表我的评论
最新评论 总共0条评论