SPRING JMS 整合ACTIVEMQ

本文介绍如何使用Spring 3.2与ActiveMQ 5.8进行整合,实现消息的异步发送和接收功能。通过配置Spring的JMS模板和消息监听器,结合ActiveMQ的连接池,演示了基于Java的异步消息处理流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

转载自:http://zld406504302.iteye.com/blog/1909751

近日用spring3.2 jms 与activemq5.8 整合一下,实现了异步发送,异步接收功能,并附上了测试代码


1 )UML 如下
   [img]
  

    消息的接受完全是托管到org.springframework.jms.listener.DefaultMessageListenerContainer 中来处理   ,发送client 无需关心消息的接受
   [/img]
2 )applicationContext.xml 片段
Java代码  收藏代码
  1. <bean id="taskExecutor"  
  2.     class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">  
  3.     <!-- 核心线程数,默认为1 -->  
  4.     <property name="corePoolSize" value="5" />  
  5.     <!-- 最大线程数,默认为Integer.MAX_VALUE -->  
  6.     <property name="maxPoolSize" value="5" />  
  7.     <!-- 队列最大长度,一般需要设置值>=notifyScheduledMainExecutor.maxNum;默认为Integer.MAX_VALUE -->  
  8.     <property name="queueCapacity" value="1000" />  
  9.     <!-- 线程池维护线程所允许的空闲时间,默认为60s -->  
  10.     <property name="keepAliveSeconds" value="300" />  
  11.     <!-- 线程池对拒绝任务(无线程可用)的处理策略,目前只支持AbortPolicy、CallerRunsPolicy;默认为后者 -->  
  12.     <property name="rejectedExecutionHandler">  
  13.         <!-- AbortPolicy:直接抛出java.util.concurrent.RejectedExecutionException异常 -->  
  14.         <!-- CallerRunsPolicy:主线程直接执行该任务,执行完之后尝试添加下一个任务到线程池中,可以有效降低向线程池内添加任务的速度 -->  
  15.         <!-- DiscardOldestPolicy:抛弃旧的任务、暂不支持;会导致被丢弃的任务无法再次被执行 -->  
  16.         <!-- DiscardPolicy:抛弃当前任务、暂不支持;会导致被丢弃的任务无法再次被执行 -->  
  17.         <bean class="java.util.concurrent.ThreadPoolExecutor$CallerRunsPolicy" />  
  18.     </property>  
  19. </bean>  
  20.          <!--jms 连接池--  
  21.            optimizedAckScheduledAckInterval:消息确认周期  
  22.   
  23.           -->  
  24.            
  25. <bean id="jmsConnectionFactory" class="org.apache.activemq.pool.PooledConnectionFactory">  
  26.     <property name="connectionFactory">  
  27.         <bean class="org.apache.activemq.ActiveMQConnectionFactory">  
  28.             <property name="brokerURL" value="tcp://localhost:61616" />  
  29.             <property name="closeTimeout" value="60000" />  
  30.             <property name="userName" value="admin" />  
  31.             <property name="password" value="admin" />  
  32.             <!--<property name="optimizeAcknowledge" value="true" />-->  
  33.             <property name="optimizedAckScheduledAckInterval" value="10000" />  
  34.         </bean>  
  35.     </property>  
  36. </bean>  
  37.   
  38. <!-- Spring JMS Template -->  
  39. <bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">  
  40.     <property name="connectionFactory">  
  41.         <ref local="jmsConnectionFactory" />  
  42.     </property>  
  43. </bean>  
  44.           
  45.          <!--queue通道-->  
  46. <bean id="asyncQueue" class="org.apache.activemq.command.ActiveMQQueue">  
  47.     <constructor-arg index="0">  
  48.         <value>asyncQueue</value>  
  49.     </constructor-arg>  
  50. </bean>  
  51.         <!--topic通道-->  
  52. <bean id="asyncTopic" name="asyncTopic"  
  53.     class="org.apache.activemq.command.ActiveMQTopic">  
  54.     <constructor-arg index="0">  
  55.         <value>asyncTopic</value>  
  56.     </constructor-arg>  
  57. </bean>  
  58.         <!--消息接受容器,多线程异步接受消息-->  
  59. <bean id="jmsContainer"  
  60.     class="org.springframework.jms.listener.DefaultMessageListenerContainer">  
  61.     <property name="connectionFactory" ref="jmsConnectionFactory" />  
  62.     <property name="destination" ref="asyncTopic" />  
  63.     <property name="messageListener" ref="messageListener" />  
  64.     <property name="sessionTransacted" value="false" />  
  65. </bean>  
  66.         <!--消息接受pojo-->  
  67. <bean id="messageReceiver" class="com.cn.ld.modules.jms.worker.JmsReceiver" />  
  68.         <!--消息发送pojo-->  
  69. <bean id="messageSender" class="com.cn.ld.modules.jms.worker.JmsSender" />  
  70.          <!--异步接收的消息监听器-->  
  71. <bean id="messageListener"  
  72.     class="org.springframework.jms.listener.adapter.MessageListenerAdapter">  
  73.     <constructor-arg>  
  74.         <ref bean="messageReceiver" />  
  75.     </constructor-arg>  
  76. </bean>  



3)java 相关class 代码
    MessageHandler 消息接受的接口
 
Java代码  收藏代码
  1. package com.cn.ld.modules.jms.handler;  
  2.   
  3. import java.io.Serializable;  
  4.   
  5. public interface MessageHandler {  
  6.     void receive(TextMessage message);  
  7.       
  8.       
  9.     void handleMessage(String message);  
  10.   
  11.     void handleMessage(Map<String, Object> message);  
  12.   
  13.     void handleMessage(byte[] message);  
  14.   
  15.     void handleMessage(Serializable message);  
  16. }  
  17.   
  18.     


  JmsReceiver  消息接受实现类
 
Java代码  收藏代码
  1.    package com.cn.ld.modules.jms.worker;  
  2.   
  3. import java.io.Serializable;  
  4.   
  5. public class JmsReceiver implements MessageHandler {  
  6.     private Collection<String> collection;  
  7.   
  8.     @Override  
  9.     public void receive(TextMessage message) {  
  10.         try {  
  11.             if (collection == null) {  
  12.                 this.collection = new ArrayList<String>();  
  13.             }  
  14.             collection.add(message.getText());  
  15.         } catch (JMSException e) {  
  16.             e.printStackTrace();  
  17.         }  
  18.     }  
  19.       
  20.       
  21.     @Override  
  22.     public void handleMessage(String message) {  
  23.         /* 
  24.          * if(collection == null){ this.collection = new ArrayList<String>(); } 
  25.          * collection.add(message); 
  26.          */  
  27.     }  
  28.   
  29.     @Override  
  30.     public void handleMessage(Map<String, Object> message) {  
  31.         Set<String> keySet = message.keySet();  
  32.         Iterator<String> keys = keySet.iterator();  
  33.         while (keys.hasNext()) {  
  34.             String key = keys.next();  
  35.             System.out.println(message.get(key));  
  36.         }  
  37.   
  38.     }  
  39.   
  40.     @Override  
  41.     public void handleMessage(byte[] message) {  
  42.   
  43.     }  
  44.   
  45.     @Override  
  46.     public void handleMessage(Serializable message) {  
  47.     }  
  48.   
  49.     public Collection<String> getCollection() {  
  50.         return collection;  
  51.     }  
  52.   
  53.     public void setCollection(Collection<String> collection) {  
  54.         this.collection = collection;  
  55.     }  
  56.   
  57. }  
  58.   
  59.     

  
  JmsSender 消息发送 支持异步发送
 
Java代码  收藏代码
  1. package com.cn.ld.modules.jms.worker;  
  2.   
  3. import java.util.Collection;  
  4.   
  5. import javax.jms.Destination;  
  6. import javax.jms.JMSException;  
  7. import javax.jms.Message;  
  8. import javax.jms.Session;  
  9.   
  10. import org.apache.activemq.command.ActiveMQTopic;  
  11. import org.springframework.beans.factory.annotation.Autowired;  
  12. import org.springframework.core.task.TaskExecutor;  
  13. import org.springframework.jms.core.JmsTemplate;  
  14. import org.springframework.jms.core.MessageCreator;  
  15. import org.springframework.util.Assert;  
  16.   
  17. import com.cn.ld.modules.annotation.MethodMonitorCount;  
  18.   
  19. public class JmsSender {  
  20.   
  21.     @Autowired  
  22.     private JmsTemplate jmsTemplate;  
  23.           
  24.     @Autowired  
  25.     private TaskExecutor taskExecutor;  
  26.   
  27.     private Destination destination;  
  28.   
  29.     private boolean isSendAsync = false;  
  30.   
  31.     public JmsSender(){}  
  32.     public JmsSender(Destination destination) {  
  33.         if (null == destination)  
  34.             this.destination = new ActiveMQTopic("topic");  
  35.         else  
  36.             this.destination = destination;  
  37.     }  
  38.   
  39.       
  40.     public void sendSingle(String message,Destination destination) {  
  41.         sendMessage(message,destination);  
  42.     }  
  43.   
  44.     public void sendBatch(Collection<?> messages,Destination destination) {  
  45.         Assert.notNull(messages, "param 'messages' can't be null !");  
  46.         Assert.notEmpty(messages, "param 'message' can't be empty !");  
  47.         for (Object message : messages) {  
  48.             if (null != message && message instanceof String) {  
  49.                 sendSingle(String.valueOf(message),destination);  
  50.             }  
  51.         }  
  52.     }  
  53.   
  54.     private void sendMessage(final String message,Destination destination) {  
  55.         final Destination sendDest = destination ;  
  56.         if (isSendAsync) {  
  57.             taskExecutor.execute(new Runnable() {  
  58.                 @Override  
  59.                 public void run() {  
  60.                     send(message,sendDest);  
  61.                 }  
  62.             });  
  63.         } else {  
  64.             send(message,destination);  
  65.         }  
  66.     }  
  67.   
  68.     private void send(final String message,Destination destination) {  
  69.         this.jmsTemplate.send(destination, new MessageCreator() {  
  70.             @Override  
  71.             public Message createMessage(Session session) throws JMSException {  
  72.                 return session.createTextMessage(message);  
  73.             }  
  74.   
  75.         });  
  76.     }  
  77.   
  78.     public boolean isSendAsync() {  
  79.         return isSendAsync;  
  80.     }  
  81.       
  82.     public void setSendAsync(boolean isSendAsync) {  
  83.         this.isSendAsync = isSendAsync;  
  84.     }  
  85.   
  86.     public Destination getDestination() {  
  87.         return destination;  
  88.     }  
  89.   
  90. }  
  91.   
  92.     

  

4) test case
Java代码  收藏代码
  1. package com.cn.ld.modules.jms;  
  2.   
  3. import java.io.File;  
  4. import java.io.IOException;  
  5.   
  6. import org.apache.activemq.command.ActiveMQTopic;  
  7. import org.apache.log4j.Logger;  
  8. import org.aspectj.util.FileUtil;  
  9. import org.junit.Before;  
  10. import org.junit.Test;  
  11. import org.junit.runner.RunWith;  
  12. import org.springframework.beans.factory.annotation.Autowired;  
  13. import org.springframework.test.context.ContextConfiguration;  
  14. import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;  
  15.   
  16. import com.cn.ld.modules.jms.worker.JmsSender;  
  17.   
  18. @RunWith(SpringJUnit4ClassRunner.class)  
  19. @ContextConfiguration(locations = { "classpath:applicationContext.xml" })  
  20. public class JmsTest {  
  21.     protected final Logger logger = Logger.getLogger(this.getClass());  
  22.   
  23.     @Autowired  
  24.     private JmsSender jmsSender;  
  25.   
  26.     private String destination;  
  27.     private int no = 1010000;  
  28.     private String message;  
  29.   
  30.     @Before  
  31.     public void init() throws IOException {  
  32.         String filePath = Thread.currentThread().getContextClassLoader()  
  33.                 .getResource("").getPath()  
  34.                 + "message.txt";  
  35.         message = FileUtil.readAsString(new File(filePath));  
  36.         this.destination = "asyncTopic";  
  37.                   //开启异步发送  
  38.         this.jmsSender.setSendAsync(true);  
  39.     }  
  40.   
  41.     @Test  
  42.     public void send() throws InterruptedException {  
  43.         ActiveMQTopic dest = new ActiveMQTopic(this.destination);  
  44.         for (int i = 0; i < no; i++) {  
  45.             jmsSender.sendSingle(message, dest);  
  46.         }  
  47.         Thread.sleep(1000000000);  
  48.     }  
  49.   

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值