转载自:http://zld406504302.iteye.com/blog/1909751
近日用spring3.2 jms 与activemq5.8 整合一下,实现了异步发送,异步接收功能,并附上了测试代码
1 )UML 如下
[img]

消息的接受完全是托管到org.springframework.jms.listener.DefaultMessageListenerContainer 中来处理 ,发送client 无需关心消息的接受
[/img]
2 )applicationContext.xml 片段
- <bean id="taskExecutor"
- class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
- <!-- 核心线程数,默认为1 -->
- <property name="corePoolSize" value="5" />
- <!-- 最大线程数,默认为Integer.MAX_VALUE -->
- <property name="maxPoolSize" value="5" />
- <!-- 队列最大长度,一般需要设置值>=notifyScheduledMainExecutor.maxNum;默认为Integer.MAX_VALUE -->
- <property name="queueCapacity" value="1000" />
- <!-- 线程池维护线程所允许的空闲时间,默认为60s -->
- <property name="keepAliveSeconds" value="300" />
- <!-- 线程池对拒绝任务(无线程可用)的处理策略,目前只支持AbortPolicy、CallerRunsPolicy;默认为后者 -->
- <property name="rejectedExecutionHandler">
- <!-- AbortPolicy:直接抛出java.util.concurrent.RejectedExecutionException异常 -->
- <!-- CallerRunsPolicy:主线程直接执行该任务,执行完之后尝试添加下一个任务到线程池中,可以有效降低向线程池内添加任务的速度 -->
- <!-- DiscardOldestPolicy:抛弃旧的任务、暂不支持;会导致被丢弃的任务无法再次被执行 -->
- <!-- DiscardPolicy:抛弃当前任务、暂不支持;会导致被丢弃的任务无法再次被执行 -->
- <bean class="java.util.concurrent.ThreadPoolExecutor$CallerRunsPolicy" />
- </property>
- </bean>
- <!--jms 连接池--
- optimizedAckScheduledAckInterval:消息确认周期
- -->
- <bean id="jmsConnectionFactory" class="org.apache.activemq.pool.PooledConnectionFactory">
- <property name="connectionFactory">
- <bean class="org.apache.activemq.ActiveMQConnectionFactory">
- <property name="brokerURL" value="tcp://localhost:61616" />
- <property name="closeTimeout" value="60000" />
- <property name="userName" value="admin" />
- <property name="password" value="admin" />
- <!--<property name="optimizeAcknowledge" value="true" />-->
- <property name="optimizedAckScheduledAckInterval" value="10000" />
- </bean>
- </property>
- </bean>
- <!-- Spring JMS Template -->
- <bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
- <property name="connectionFactory">
- <ref local="jmsConnectionFactory" />
- </property>
- </bean>
- <!--queue通道-->
- <bean id="asyncQueue" class="org.apache.activemq.command.ActiveMQQueue">
- <constructor-arg index="0">
- <value>asyncQueue</value>
- </constructor-arg>
- </bean>
- <!--topic通道-->
- <bean id="asyncTopic" name="asyncTopic"
- class="org.apache.activemq.command.ActiveMQTopic">
- <constructor-arg index="0">
- <value>asyncTopic</value>
- </constructor-arg>
- </bean>
- <!--消息接受容器,多线程异步接受消息-->
- <bean id="jmsContainer"
- class="org.springframework.jms.listener.DefaultMessageListenerContainer">
- <property name="connectionFactory" ref="jmsConnectionFactory" />
- <property name="destination" ref="asyncTopic" />
- <property name="messageListener" ref="messageListener" />
- <property name="sessionTransacted" value="false" />
- </bean>
- <!--消息接受pojo-->
- <bean id="messageReceiver" class="com.cn.ld.modules.jms.worker.JmsReceiver" />
- <!--消息发送pojo-->
- <bean id="messageSender" class="com.cn.ld.modules.jms.worker.JmsSender" />
- <!--异步接收的消息监听器-->
- <bean id="messageListener"
- class="org.springframework.jms.listener.adapter.MessageListenerAdapter">
- <constructor-arg>
- <ref bean="messageReceiver" />
- </constructor-arg>
- </bean>
3)java 相关class 代码
MessageHandler 消息接受的接口
- package com.cn.ld.modules.jms.handler;
- import java.io.Serializable;
- public interface MessageHandler {
- void receive(TextMessage message);
- void handleMessage(String message);
- void handleMessage(Map<String, Object> message);
- void handleMessage(byte[] message);
- void handleMessage(Serializable message);
- }
JmsReceiver 消息接受实现类
- package com.cn.ld.modules.jms.worker;
- import java.io.Serializable;
- public class JmsReceiver implements MessageHandler {
- private Collection<String> collection;
- @Override
- public void receive(TextMessage message) {
- try {
- if (collection == null) {
- this.collection = new ArrayList<String>();
- }
- collection.add(message.getText());
- } catch (JMSException e) {
- e.printStackTrace();
- }
- }
- @Override
- public void handleMessage(String message) {
- /*
- * if(collection == null){ this.collection = new ArrayList<String>(); }
- * collection.add(message);
- */
- }
- @Override
- public void handleMessage(Map<String, Object> message) {
- Set<String> keySet = message.keySet();
- Iterator<String> keys = keySet.iterator();
- while (keys.hasNext()) {
- String key = keys.next();
- System.out.println(message.get(key));
- }
- }
- @Override
- public void handleMessage(byte[] message) {
- }
- @Override
- public void handleMessage(Serializable message) {
- }
- public Collection<String> getCollection() {
- return collection;
- }
- public void setCollection(Collection<String> collection) {
- this.collection = collection;
- }
- }
JmsSender 消息发送 支持异步发送
- package com.cn.ld.modules.jms.worker;
- import java.util.Collection;
- import javax.jms.Destination;
- import javax.jms.JMSException;
- import javax.jms.Message;
- import javax.jms.Session;
- import org.apache.activemq.command.ActiveMQTopic;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.core.task.TaskExecutor;
- import org.springframework.jms.core.JmsTemplate;
- import org.springframework.jms.core.MessageCreator;
- import org.springframework.util.Assert;
- import com.cn.ld.modules.annotation.MethodMonitorCount;
- public class JmsSender {
- @Autowired
- private JmsTemplate jmsTemplate;
- @Autowired
- private TaskExecutor taskExecutor;
- private Destination destination;
- private boolean isSendAsync = false;
- public JmsSender(){}
- public JmsSender(Destination destination) {
- if (null == destination)
- this.destination = new ActiveMQTopic("topic");
- else
- this.destination = destination;
- }
- public void sendSingle(String message,Destination destination) {
- sendMessage(message,destination);
- }
- public void sendBatch(Collection<?> messages,Destination destination) {
- Assert.notNull(messages, "param 'messages' can't be null !");
- Assert.notEmpty(messages, "param 'message' can't be empty !");
- for (Object message : messages) {
- if (null != message && message instanceof String) {
- sendSingle(String.valueOf(message),destination);
- }
- }
- }
- private void sendMessage(final String message,Destination destination) {
- final Destination sendDest = destination ;
- if (isSendAsync) {
- taskExecutor.execute(new Runnable() {
- @Override
- public void run() {
- send(message,sendDest);
- }
- });
- } else {
- send(message,destination);
- }
- }
- private void send(final String message,Destination destination) {
- this.jmsTemplate.send(destination, new MessageCreator() {
- @Override
- public Message createMessage(Session session) throws JMSException {
- return session.createTextMessage(message);
- }
- });
- }
- public boolean isSendAsync() {
- return isSendAsync;
- }
- public void setSendAsync(boolean isSendAsync) {
- this.isSendAsync = isSendAsync;
- }
- public Destination getDestination() {
- return destination;
- }
- }
4) test case
- package com.cn.ld.modules.jms;
- import java.io.File;
- import java.io.IOException;
- import org.apache.activemq.command.ActiveMQTopic;
- import org.apache.log4j.Logger;
- import org.aspectj.util.FileUtil;
- import org.junit.Before;
- import org.junit.Test;
- import org.junit.runner.RunWith;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.test.context.ContextConfiguration;
- import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
- import com.cn.ld.modules.jms.worker.JmsSender;
- @RunWith(SpringJUnit4ClassRunner.class)
- @ContextConfiguration(locations = { "classpath:applicationContext.xml" })
- public class JmsTest {
- protected final Logger logger = Logger.getLogger(this.getClass());
- @Autowired
- private JmsSender jmsSender;
- private String destination;
- private int no = 10* 10000;
- private String message;
- @Before
- public void init() throws IOException {
- String filePath = Thread.currentThread().getContextClassLoader()
- .getResource("").getPath()
- + "message.txt";
- message = FileUtil.readAsString(new File(filePath));
- this.destination = "asyncTopic";
- //开启异步发送
- this.jmsSender.setSendAsync(true);
- }
- @Test
- public void send() throws InterruptedException {
- ActiveMQTopic dest = new ActiveMQTopic(this.destination);
- for (int i = 0; i < no; i++) {
- jmsSender.sendSingle(message, dest);
- }
- Thread.sleep(1000000000);
- }
- }