Spring整合ActiveMQ实现简单的消息队列

Spring整合ActiveMQ实现简单的消息队列

JMS简介

JMS(Java Message Service),Java消息服务。主要用于在生产者和消费者之间进行消息传送,生产者负责生产消息,消费者负责接收处理消息。在实际的业务中,生产者生成消息,发送消息,消息会保存到ActiveMQ队列中,对应的消费者会接收消息,完成特定的业务逻辑。消息的传递模型有两种,一种是点对点,一个生产者对应一个消费者;另一种是发布订阅模式,一个生产者对应多个消费者,Java应用和ActiveMQ之间使用JMS传送消息。

Spring整合ActiveMQ

引入依赖

maven依赖如下

 

  1. <dependency>  
  2.     <groupId>org.apache.activemq</groupId>  
  3.     <artifactId>activemq-all</artifactId>  
  4.     <version>5.14.5</version>  
  5. </dependency>   
  6. <dependency>  
  7.     <groupId>javax.annotation</groupId>  
  8.     <artifactId>jsr250-api</artifactId>  
  9.     <version>1.0</version>  
  10. </dependency>  
  11.    <span style=“white-space:pre”>   </span><dependency>    
  12.            <groupId>org.springframework</groupId>    
  13.            <artifactId>spring-messaging</artifactId>    
  14.            <version>{spring.version}</span><span class="tag">&lt;/</span><span class="tag-name">version</span><span class="tag">&gt;</span><span>&nbsp;&nbsp;&nbsp;&nbsp;</span></span></li><li class="alt"><span>&nbsp;&nbsp;&nbsp;<span class="tag">&lt;</span><span class="tag-name">span</span><span>&nbsp;</span><span class="attribute">style</span><span>=</span><span class="attribute-value">"white-space:pre"</span><span class="tag">&gt;</span><span>&nbsp;&nbsp;&nbsp;</span><span class="tag">&lt;/</span><span class="tag-name">span</span><span class="tag">&gt;</span><span class="tag">&lt;/</span><span class="tag-name">dependency</span><span class="tag">&gt;</span><span>&nbsp;&nbsp;</span></span></li><li class=""><span>&nbsp;&nbsp;&nbsp;<span class="tag">&lt;</span><span class="tag-name">span</span><span>&nbsp;</span><span class="attribute">style</span><span>=</span><span class="attribute-value">"white-space:pre"</span><span class="tag">&gt;</span><span>&nbsp;&nbsp;&nbsp;</span><span class="tag">&lt;/</span><span class="tag-name">span</span><span class="tag">&gt;</span><span class="tag">&lt;</span><span class="tag-name">dependency</span><span class="tag">&gt;</span><span>&nbsp;&nbsp;&nbsp;&nbsp;</span></span></li><li class="alt"><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="tag">&lt;</span><span class="tag-name">groupId</span><span class="tag">&gt;</span><span>org.springframework</span><span class="tag">&lt;/</span><span class="tag-name">groupId</span><span class="tag">&gt;</span><span>&nbsp;&nbsp;&nbsp;&nbsp;</span></span></li><li class=""><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="tag">&lt;</span><span class="tag-name">artifactId</span><span class="tag">&gt;</span><span>spring-jms</span><span class="tag">&lt;/</span><span class="tag-name">artifactId</span><span class="tag">&gt;</span><span>&nbsp;&nbsp;&nbsp;&nbsp;</span></span></li><li class="alt"><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="tag">&lt;</span><span class="tag-name">version</span><span class="tag">&gt;</span><span>{spring.version}</version>    
  15.    <span style=“white-space:pre”>   </span></dependency>  
  16. <dependency>  
  17.     <groupId>org.apache.xbean</groupId>  
  18.     <artifactId>xbean-spring</artifactId>  
  19.     <version>4.5</version>  
  20. </dependency>  
<dependency>
   <groupId>org.apache.activemq</groupId>
   <artifactId>activemq-all</artifactId>
   <version>5.14.5</version>
</dependency>
<dependency>
   <groupId>javax.annotation</groupId>
   <artifactId>jsr250-api</artifactId>
   <version>1.0</version>
</dependency>
     <dependency>  
            <groupId>org.springframework</groupId>  
            <artifactId>spring-messaging</artifactId>  
            <version>${spring.version}</version>  
     </dependency>
     <dependency>  
            <groupId>org.springframework</groupId>  
            <artifactId>spring-jms</artifactId>  
            <version>${spring.version}</version>  
     </dependency>
<dependency>
   <groupId>org.apache.xbean</groupId>
   <artifactId>xbean-spring</artifactId>
   <version>4.5</version>
</dependency>

Spring中配置ActiveMQ

完整配置文件为:

 

  1. <?xml version=“1.0” encoding=“UTF-8”?>  
  2. <beans xmlns=“http://www.springframework.org/schema/beans”  
  3.         xmlns:context=“http://www.springframework.org/schema/context” xmlns:p=“http://www.springframework.org/schema/p”  
  4.         xmlns:mvc=“http://www.springframework.org/schema/mvc” xmlns:tx=“http://www.springframework.org/schema/tx”  
  5.         xmlns:aop=“http://www.springframework.org/schema/aop” xmlns:xsi=“http://www.w3.org/2001/XMLSchema-instance”  
  6.         xmlns:jms=“http://www.springframework.org/schema/jms” xmlns:amq=“http://activemq.apache.org/schema/core”  
  7.         xsi:schemaLocation=”http://www.springframework.org/schema/beans    
  8.       http://www.springframework.org/schema/beans/spring-beans-4.0.xsd    
  9.       http://www.springframework.org/schema/context    
  10.       http://www.springframework.org/schema/context/spring-context-4.0.xsd    
  11.       http://www.springframework.org/schema/mvc    
  12.       http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd  
  13.       http://www.springframework.org/schema/tx    
  14.       http://www.springframework.org/schema/tx/spring-tx-4.0.xsd  
  15.       http://www.springframework.org/schema/aop    
  16.       http://www.springframework.org/schema/aop/spring-aop-4.0.xsd  
  17.       http://www.springframework.org/schema/jms    
  18.       http://www.springframework.org/schema/jms/spring-jms-4.0.xsd  
  19.       http://activemq.apache.org/schema/core  
  20.       http://activemq.apache.org/schema/core/activemq-core-5.14.5.xsd”>  
  21.         
  22.       <!–activemq连接工厂 –>  
  23.       <amq:connectionFactory id=“activemqConnectionFactory” brokerURL=“tcp://127.0.0.1:61616” userName=“admin” password=“admin”></amq:connectionFactory>  
  24.         
  25.       <!–spring连接工厂,管理activemq连接工厂 –>  
  26.       <bean id=“connectionFactory” class=“org.springframework.jms.connection.CachingConnectionFactory”>  
  27.         <!–管理对象,对应activemq连接工厂  –>  
  28.         <property name=“targetConnectionFactory” ref=“activemqConnectionFactory”></property>  
  29.         <!–session缓存数量  –>  
  30.         <property name=“sessionCacheSize” value=“100”/>  
  31.       </bean>  
  32.         
  33.       <!–定义消息队列  –>  
  34.       <bean id=“tttQueueDestination” class=“org.apache.activemq.command.ActiveMQQueue”>  
  35.         <!–消息队列名称  –>  
  36.         <constructor-arg>  
  37.             <value>ttt.queue</value>  
  38.         </constructor-arg>  
  39.       </bean>  
  40.         
  41.       <bean id=“tttTopicDestination” class=“org.apache.activemq.command.ActiveMQTopic”>  
  42.         <!–订阅主题名称  –>  
  43.         <constructor-arg>  
  44.             <value>ttt.topic</value>  
  45.         </constructor-arg>  
  46.       </bean>  
  47.         
  48.       <!–消息生产者  –>  
  49.       <!–队列类型JmsTemplate  –>  
  50.       <bean id=“jmsQueueTemplate” class=“org.springframework.jms.core.JmsTemplate”>  
  51.         <property name=“connectionFactory” ref=“connectionFactory”/>  
  52.         <property name=“defaultDestination” ref=“tttQueueDestination”/>  
  53.         <property name=“receiveTimeout” value=“10000”/>  
  54.         <!–非pub/sub(发布/订阅)模式,即队列模式 –>  
  55.         <property name=“pubSubDomain” value=“false”/>  
  56.       </bean>  
  57.         
  58.       <!–Topic类型JmsTemplate  –>  
  59.       <bean id=“jmsTopicTemplate” class=“org.springframework.jms.core.JmsTemplate”>  
  60.         <property name=“connectionFactory” ref=“connectionFactory”/>  
  61.         <property name=“defaultDestination” ref=“tttTopicDestination”/>  
  62.         <property name=“receiveTimeout” value=“10000”/>  
  63.         <!–pub/sub(发布/订阅)模式 –>  
  64.         <property name=“pubSubDomain” value=“true”/>        
  65.       </bean>  
  66.         
  67.       <!–消息消费者–>  
  68.         
  69.       <jms:listener-container destination-type=“queue” container-type=“default” connection-factory=“connectionFactory” acknowledge=“auto”>  
  70.         <!–队列监听器  –>  
  71.         <jms:listener destination=“ttt.queue” ref=“queueListener”/>  
  72.       </jms:listener-container>  
  73.         
  74.       <jms:listener-container destination-type=“topic” container-type=“default” connection-factory=“connectionFactory” acknowledge=“auto”>  
  75.         <!–Topic监听器  –>  
  76.         <jms:listener destination=“ttt.topic” ref=“topicListener”/>  
  77.       </jms:listener-container>  
  78. </beans>  
<?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:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx"
        xmlns:aop="http://www.springframework.org/schema/aop" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:jms="http://www.springframework.org/schema/jms" 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://www.springframework.org/schema/context  
      http://www.springframework.org/schema/context/spring-context-4.0.xsd  
      http://www.springframework.org/schema/mvc  
      http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
      http://www.springframework.org/schema/tx  
      http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
      http://www.springframework.org/schema/aop  
      http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
      http://www.springframework.org/schema/jms  
      http://www.springframework.org/schema/jms/spring-jms-4.0.xsd
      http://activemq.apache.org/schema/core
      http://activemq.apache.org/schema/core/activemq-core-5.14.5.xsd">

      <!--activemq连接工厂 -->
      <amq:connectionFactory id="activemqConnectionFactory" brokerURL="tcp://127.0.0.1:61616" userName="admin" password="admin"></amq:connectionFactory>

      <!--spring连接工厂,管理activemq连接工厂 -->
      <bean id="connectionFactory" class="org.springframework.jms.connection.CachingConnectionFactory">
      <!--管理对象,对应activemq连接工厂  -->
      <property name="targetConnectionFactory" ref="activemqConnectionFactory"></property>
      <!--session缓存数量  -->
      <property name="sessionCacheSize" value="100"/>
      </bean>

      <!--定义消息队列  -->
      <bean id="tttQueueDestination" class="org.apache.activemq.command.ActiveMQQueue">
      <!--消息队列名称  -->
      <constructor-arg>
      <value>ttt.queue</value>
      </constructor-arg>
      </bean>

      <bean id="tttTopicDestination" class="org.apache.activemq.command.ActiveMQTopic">
      <!--订阅主题名称  -->
      <constructor-arg>
      <value>ttt.topic</value>
      </constructor-arg>
      </bean>

      <!--消息生产者  -->
      <!--队列类型JmsTemplate  -->
      <bean id="jmsQueueTemplate" class="org.springframework.jms.core.JmsTemplate">
      <property name="connectionFactory" ref="connectionFactory"/>
      <property name="defaultDestination" ref="tttQueueDestination"/>
      <property name="receiveTimeout" value="10000"/>
      <!--非pub/sub(发布/订阅)模式,即队列模式 -->
      <property name="pubSubDomain" value="false"/>
      </bean>

      <!--Topic类型JmsTemplate  -->
      <bean id="jmsTopicTemplate" class="org.springframework.jms.core.JmsTemplate">
      <property name="connectionFactory" ref="connectionFactory"/>
      <property name="defaultDestination" ref="tttTopicDestination"/>
      <property name="receiveTimeout" value="10000"/>
      <!--pub/sub(发布/订阅)模式 -->
      <property name="pubSubDomain" value="true"/>      
      </bean>

      <!--消息消费者-->

      <jms:listener-container destination-type="queue" container-type="default" connection-factory="connectionFactory" acknowledge="auto">
      <!--队列监听器  -->
      <jms:listener destination="ttt.queue" ref="queueListener"/>
      </jms:listener-container>

      <jms:listener-container destination-type="topic" container-type="default" connection-factory="connectionFactory" acknowledge="auto">
      <!--Topic监听器  -->
      <jms:listener destination="ttt.topic" ref="topicListener"/>
      </jms:listener-container>
</beans>

发送消息

发送Queue消息

收到发送Queue的请求,创建队列消息发送对象,设置消息业务处理逻辑bean、数据,发送消息

 

  1. @Override  
  2. public void sendQueueMessage() {  
  3.     Random r = new Random();  
  4.     Map<String, Object> map = new HashMap<String, Object>();  
  5.     map.put(”message” + r.nextInt(100), r.nextInt(10000));  
  6.     MessageSender sender = new MessageSender(“asyncProcessor.message”);  
  7.     sender.sendMessage(map);  
  8. }  
 @Override
public void sendQueueMessage() {
Random r = new Random();
Map<String, Object> map = new HashMap<String, Object>();
map.put("message" + r.nextInt(100), r.nextInt(10000));
MessageSender sender = new MessageSender("asyncProcessor.message");
sender.sendMessage(map);
}

队列消息发送对象

 

  1. public class MessageSender implements Serializable {  
  2.   
  3.     /** 
  4.      *  
  5.      */  
  6.     private static final long serialVersionUID = -7611739730866180422L;  
  7.   
  8.     private String bean;  
  9.   
  10.     public MessageSender(String bean) {  
  11.         this.bean = bean;  
  12.     }  
  13.   
  14.     public String getBean() {  
  15.         return bean;  
  16.     }  
  17.   
  18.     public void sendMessage(Destination destination, Map<String, Object> map) {  
  19.         MessageHelper.sendMessage(destination, map, getBean());  
  20.     }  
  21.   
  22.     public void sendMessage(Map<String, Object> map) {  
  23.         MessageHelper.sendMessage(map, getBean());  
  24.     }  
  25.   
  26. }  
public class MessageSender implements Serializable {


/**
* 
*/
private static final long serialVersionUID = -7611739730866180422L;


private String bean;


public MessageSender(String bean) {
this.bean = bean;
}


public String getBean() {
return bean;
}


public void sendMessage(Destination destination, Map<String, Object> map) {
MessageHelper.sendMessage(destination, map, getBean());
}


public void sendMessage(Map<String, Object> map) {
MessageHelper.sendMessage(map, getBean());
}


}

调用jmsTemplate发送队列消息

 

  1. @Component  
  2. public class MessageHelper implements Serializable, InitializingBean {  
  3.   
  4.     /** 
  5.      *  
  6.      */  
  7.     private static final long serialVersionUID = 522520461829363235L;  
  8.   
  9.     @Autowired  
  10.     private JmsTemplate jmsQueueTemplate;  
  11.   
  12.     private static JmsTemplate jmsTemplateProxy;  
  13.   
  14.     public JmsTemplate getJmsTemplate() {  
  15.         return jmsQueueTemplate;  
  16.     }  
  17.   
  18.     public void setJmsTemplate(JmsTemplate jmsTemplate) {  
  19.         this.jmsQueueTemplate = jmsTemplate;  
  20.     }  
  21.   
  22.     public static void sendMessage(Destination destination, final Map<String, Object> map, String processor) {  
  23.         jmsTemplateProxy.send(destination, new MessageCreator() {  
  24.   
  25.             @Override  
  26.             public Message createMessage(Session session) throws JMSException {  
  27.                 MapMessage message = session.createMapMessage();  
  28.                 message.setString(”processor”, processor);  
  29.                 message.setObject(”data”, map);  
  30.                 message.setJMSDestination(destination);  
  31.                 return message;  
  32.             }  
  33.         });  
  34.     }  
  35.   
  36.     public static void sendMessage(Map<String, Object> map, String processor) {  
  37.         jmsTemplateProxy.send(new MessageCreator() {  
  38.   
  39.             @Override  
  40.             public Message createMessage(Session session) throws JMSException {  
  41.                 MapMessage message = session.createMapMessage();  
  42.                 message.setObject(”processor”, processor);  
  43.                 message.setObject(”data”, map);  
  44.                 return message;  
  45.             }  
  46.         });  
  47.     }  
  48.   
  49.     @Override  
  50.     public void afterPropertiesSet() throws Exception {  
  51.   
  52.         jmsTemplateProxy = this.jmsQueueTemplate;  
  53.     }  
  54.   
  55.     public static JmsTemplate getJmsTemplateProxy() {  
  56.         return jmsTemplateProxy;  
  57.     }  
  58.   
  59.     public static void setJmsTemplateProxy(JmsTemplate jmsTemplateProxy) {  
  60.         MessageHelper.jmsTemplateProxy = jmsTemplateProxy;  
  61.     }  
  62. }  
@Component
public class MessageHelper implements Serializable, InitializingBean {


/**
* 
*/
private static final long serialVersionUID = 522520461829363235L;


@Autowired
private JmsTemplate jmsQueueTemplate;


private static JmsTemplate jmsTemplateProxy;


public JmsTemplate getJmsTemplate() {
return jmsQueueTemplate;
}


public void setJmsTemplate(JmsTemplate jmsTemplate) {
this.jmsQueueTemplate = jmsTemplate;
}


public static void sendMessage(Destination destination, final Map<String, Object> map, String processor) {
jmsTemplateProxy.send(destination, new MessageCreator() {


@Override
public Message createMessage(Session session) throws JMSException {
MapMessage message = session.createMapMessage();
message.setString("processor", processor);
message.setObject("data", map);
message.setJMSDestination(destination);
return message;
}
});
}


public static void sendMessage(Map<String, Object> map, String processor) {
jmsTemplateProxy.send(new MessageCreator() {


@Override
public Message createMessage(Session session) throws JMSException {
MapMessage message = session.createMapMessage();
message.setObject("processor", processor);
message.setObject("data", map);
return message;
}
});
}


@Override
public void afterPropertiesSet() throws Exception {


jmsTemplateProxy = this.jmsQueueTemplate;
}


public static JmsTemplate getJmsTemplateProxy() {
return jmsTemplateProxy;
}


public static void setJmsTemplateProxy(JmsTemplate jmsTemplateProxy) {
MessageHelper.jmsTemplateProxy = jmsTemplateProxy;
}
}

发送Topic消息

 

收到发送Topic的请求,创建Topic消息发送对象,设置消息业务处理逻辑bean、数据,发送消息

 

  1. @Override  
  2.     public void sendTopicMessage() {  
  3.         Random r = new Random();  
  4.         Map<String, Object> map = new HashMap<String, Object>();  
  5.         map.put(”topic” + r.nextInt(100), r.nextInt(10000));  
  6.         TopicSender sender = new TopicSender(“asyncProcessor.topic”);  
  7.         sender.sendTopic(map);  
  8.     }  
@Override
public void sendTopicMessage() {
Random r = new Random();
Map<String, Object> map = new HashMap<String, Object>();
map.put("topic" + r.nextInt(100), r.nextInt(10000));
TopicSender sender = new TopicSender("asyncProcessor.topic");
sender.sendTopic(map);
}

Topic消息发送对象类

 

  1. public class TopicSender implements Serializable {  
  2.   
  3.     /** 
  4.      *  
  5.      */  
  6.     private static final long serialVersionUID = -2422605328103788546L;  
  7.   
  8.     private String processor;  
  9.   
  10.     public TopicSender(String processor) {  
  11.         this.processor = processor;  
  12.     }  
  13.   
  14.     public String getProcessor() {  
  15.         return processor;  
  16.     }  
  17.   
  18.     public void setProcessor(String processor) {  
  19.         this.processor = processor;  
  20.     }  
  21.   
  22.     public void sendTopic(Destination destination, Map<String, Object> map) {  
  23.         TopicHelper.send(destination, map, getProcessor());  
  24.     }  
  25.   
  26.     public void sendTopic(Map<String, Object> map) {  
  27.         TopicHelper.send(map, getProcessor());  
  28.     }  
  29. }  
public class TopicSender implements Serializable {


/**
* 
*/
private static final long serialVersionUID = -2422605328103788546L;


private String processor;


public TopicSender(String processor) {
this.processor = processor;
}


public String getProcessor() {
return processor;
}


public void setProcessor(String processor) {
this.processor = processor;
}


public void sendTopic(Destination destination, Map<String, Object> map) {
TopicHelper.send(destination, map, getProcessor());
}


public void sendTopic(Map<String, Object> map) {
TopicHelper.send(map, getProcessor());
}
}

调用jmsTemplate发送Topic消息

 

  1. @Component  
  2. public class TopicHelper implements Serializable, InitializingBean {  
  3.   
  4.     /** 
  5.      *  
  6.      */  
  7.     private static final long serialVersionUID = 2255365346654153127L;  
  8.   
  9.     @Autowired  
  10.     private JmsTemplate jmsTopicTemplate;  
  11.   
  12.     private static JmsTemplate jmsTopicTemplateProxy;  
  13.   
  14.     public static JmsTemplate getJmsTemplateProxy() {  
  15.         return jmsTopicTemplateProxy;  
  16.     }  
  17.   
  18.     public static void send(Destination destination, final Map<String, Object> map, final String processor) {  
  19.         jmsTopicTemplateProxy.send(destination, new MessageCreator() {  
  20.   
  21.             @Override  
  22.             public Message createMessage(Session session) throws JMSException {  
  23.                 MapMessage message = session.createMapMessage();  
  24.                 message.setString(”processor”, processor);  
  25.                 message.setObject(”data”, map);  
  26.                 return message;  
  27.             }  
  28.         });  
  29.     }  
  30.   
  31.     public static void send(final Map<String, Object> map, final String processor) {  
  32.         jmsTopicTemplateProxy.send(new MessageCreator() {  
  33.   
  34.             @Override  
  35.             public Message createMessage(Session session) throws JMSException {  
  36.                 MapMessage message = session.createMapMessage();  
  37.                 message.setString(”processor”, processor);  
  38.                 message.setObject(”data”, map);  
  39.                 return message;  
  40.             }  
  41.         });  
  42.     }  
  43.   
  44.     public JmsTemplate getJmsTopicTemplate() {  
  45.         return jmsTopicTemplate;  
  46.     }  
  47.   
  48.     public void setJmsTopicTemplate(JmsTemplate jmsTopicTemplate) {  
  49.         this.jmsTopicTemplate = jmsTopicTemplate;  
  50.     }  
  51.   
  52.     @Override  
  53.     public void afterPropertiesSet() throws Exception {  
  54.         jmsTopicTemplateProxy = getJmsTopicTemplate();  
  55.     }  
  56. }  
@Component
public class TopicHelper implements Serializable, InitializingBean {


/**
* 
*/
private static final long serialVersionUID = 2255365346654153127L;


@Autowired
private JmsTemplate jmsTopicTemplate;


private static JmsTemplate jmsTopicTemplateProxy;


public static JmsTemplate getJmsTemplateProxy() {
return jmsTopicTemplateProxy;
}


public static void send(Destination destination, final Map<String, Object> map, final String processor) {
jmsTopicTemplateProxy.send(destination, new MessageCreator() {


@Override
public Message createMessage(Session session) throws JMSException {
MapMessage message = session.createMapMessage();
message.setString("processor", processor);
message.setObject("data", map);
return message;
}
});
}


public static void send(final Map<String, Object> map, final String processor) {
jmsTopicTemplateProxy.send(new MessageCreator() {


@Override
public Message createMessage(Session session) throws JMSException {
MapMessage message = session.createMapMessage();
message.setString("processor", processor);
message.setObject("data", map);
return message;
}
});
}


public JmsTemplate getJmsTopicTemplate() {
return jmsTopicTemplate;
}


public void setJmsTopicTemplate(JmsTemplate jmsTopicTemplate) {
this.jmsTopicTemplate = jmsTopicTemplate;
}


@Override
public void afterPropertiesSet() throws Exception {
jmsTopicTemplateProxy = getJmsTopicTemplate();
}
}

监听消息

监听队列消息

配置监听

  1. <jms:listener-container destination-type=“queue” container-type=“default” connection-factory=“connectionFactory” acknowledge=“auto”>  
  2.     <!–队列监听器  –>  
  3.     <jms:listener destination=“ttt.queue” ref=“queueListener”/>  
  4. </jms:listener-container>  
      <jms:listener-container destination-type="queue" container-type="default" connection-factory="connectionFactory" acknowledge="auto">
      <!--队列监听器  -->
      <jms:listener destination="ttt.queue" ref="queueListener"/>
      </jms:listener-container>

监听实现

  1. @Component  
  2. public class QueueListener implements MessageListener {  
  3.   
  4.     private static final Logger log = LoggerFactory.getLogger(MessageListener.class);  
  5.   
  6.     @SuppressWarnings(“unchecked”)  
  7.     @Override  
  8.     public void onMessage(Message message) {  
  9.         MapMessage msg = (MapMessage) message;  
  10.         try {  
  11.             String processorName = msg.getString(”processor”);  
  12.             Map<String, Object> param = (Map<String, Object>) msg.getObject(”data”);  
  13.             IAsyncProcessor processor = (IAsyncProcessor) Context.getApplicationContext().getBean(processorName);  
  14.             processor.process(param);  
  15.         } catch (JMSException e) {  
  16.   
  17.             log.error(”QueueListener on message error|”, e);  
  18.         }  
  19.     }  
  20.   
  21. }  
@Component
public class QueueListener implements MessageListener {


private static final Logger log = LoggerFactory.getLogger(MessageListener.class);


@SuppressWarnings("unchecked")
@Override
public void onMessage(Message message) {
MapMessage msg = (MapMessage) message;
try {
String processorName = msg.getString("processor");
Map<String, Object> param = (Map<String, Object>) msg.getObject("data");
IAsyncProcessor processor = (IAsyncProcessor) Context.getApplicationContext().getBean(processorName);
processor.process(param);
} catch (JMSException e) {


log.error("QueueListener on message error|", e);
}
}


}


监听Topic消息

配置监听

  1. <jms:listener-container destination-type=“topic” container-type=“default” connection-factory=“connectionFactory” acknowledge=“auto”>  
  2.     <!–Topic监听器  –>  
  3.     <jms:listener destination=“ttt.topic” ref=“topicListener”/>  
  4. </jms:listener-container>  
      <jms:listener-container destination-type="topic" container-type="default" connection-factory="connectionFactory" acknowledge="auto">
      <!--Topic监听器  -->
      <jms:listener destination="ttt.topic" ref="topicListener"/>
      </jms:listener-container>

监听实现

 

  1. @Component  
  2. public class TopicListener implements MessageListener {  
  3.   
  4.     private static final Logger log = LoggerFactory.getLogger(MessageListener.class);  
  5.   
  6.     @SuppressWarnings(“unchecked”)  
  7.     @Override  
  8.     public void onMessage(Message message) {  
  9.         MapMessage msg = (MapMessage) message;  
  10.         try {  
  11.             String processorName = msg.getString(”processor”);  
  12.             Map<String, Object> param = (Map<String, Object>) msg.getObject(”data”);  
  13.             IAsyncProcessor processor = (IAsyncProcessor) Context.getApplicationContext().getBean(processorName);  
  14.             processor.process(param);  
  15.         } catch (JMSException e) {  
  16.   
  17.             log.error(”TopicListener on message error|”, e);  
  18.         }  
  19.     }  
  20.   
  21. }  
@Component
public class TopicListener implements MessageListener {


private static final Logger log = LoggerFactory.getLogger(MessageListener.class);


@SuppressWarnings("unchecked")
@Override
public void onMessage(Message message) {
MapMessage msg = (MapMessage) message;
try {
String processorName = msg.getString("processor");
Map<String, Object> param = (Map<String, Object>) msg.getObject("data");
IAsyncProcessor processor = (IAsyncProcessor) Context.getApplicationContext().getBean(processorName);
processor.process(param);
} catch (JMSException e) {


log.error("TopicListener on message error|", e);
}
}


}

业务处理

业务逻辑处理bean实现

 接口

  1. public interface IAsyncProcessor {  
  2.   
  3.     /** 
  4.      * 逻辑处理 
  5.      *  
  6.      * @param map 
  7.      */  
  8.     public void process(Map<String, Object> map);  
  9. }  
public interface IAsyncProcessor {


/**
* 逻辑处理
* 
* @param map
*/
public void process(Map<String, Object> map);
}

实现

  1. @Named(“asyncProcessor.message”)  
  2. public class MessageAsyncProcessor implements IAsyncProcessor {  
  3.   
  4.     @Override  
  5.     public void process(Map<String, Object> map) {  
  6.         for (Entry<String, Object> e : map.entrySet()) {  
  7.             System.out.println(”message:” + e.getKey() + “,” + e.getValue());  
  8.         }  
  9.   
  10.     }  
  11.   
  12. }  
@Named("asyncProcessor.message")
public class MessageAsyncProcessor implements IAsyncProcessor {


@Override
public void process(Map<String, Object> map) {
for (Entry<String, Object> e : map.entrySet()) {
System.out.println("message:" + e.getKey() + "," + e.getValue());
}


}


}
  1. @Named(“asyncProcessor.topic”)  
  2. public class TopicAsyncProcessor implements IAsyncProcessor {  
  3.   
  4.     @Override  
  5.     public void process(Map<String, Object> map) {  
  6.         for (Entry<String, Object> e : map.entrySet()) {  
  7.             System.out.println(”topic:” + e.getKey() + “,” + e.getValue());  
  8.         }  
  9.     }  
  10.   
  11. }  
@Named("asyncProcessor.topic")
public class TopicAsyncProcessor implements IAsyncProcessor {


@Override
public void process(Map<String, Object> map) {
for (Entry<String, Object> e : map.entrySet()) {
System.out.println("topic:" + e.getKey() + "," + e.getValue());
}
}


}


获取业务逻辑处理bean的context代码

  1. @Component  
  2. public class Context implements ApplicationContextAware {  
  3.   
  4.     private static ApplicationContext context;  
  5.   
  6.     @Override  
  7.     public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {  
  8.         context = applicationContext;  
  9.     }  
  10.   
  11.     public static ApplicationContext getApplicationContext() {  
  12.         return context;  
  13.     }  
  14.   
  15. }  
@Component
public class Context implements ApplicationContextAware {


private static ApplicationContext context;


@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
context = applicationContext;
}


public static ApplicationContext getApplicationContext() {
return context;
}


}

碰到问题

 引入Activemq-all新版本jar包后,activemq中的Spring部分和Spring重复,会导致spring启动报错,只需要包activemq中的spring部分删除即可以正常运行。


(完)。

转自:http://blog.csdn.net/weihao_/article/details/74454736

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值