---
title: "使用Spring和ActiveMQ实现高效的轻量级的JMS  "
author: "isoftyh"
date: "2013-03-15T22:13:49Z"
tags: []
categories: ["互联网"]
slug: "spring-activemq-jms"
draft: false
lastmod: "2013-03-15T22:13:49Z"
id: 1830294
url: "https://isoftyh.iteye.com/blog/1830294"
---

转载自：http://windows9834.blog.163.com/blog/static/27345004201311841121335/

这是官方推荐要看的原文的翻译：[http://codedependents.com/2009/10/16/efficient-lightweight-jms-with-spring-and-activemq/](http://codedependents.com/2009/10/16/efficient-lightweight-jms-with-spring-and-activemq/)

 

异步性（asynchronicity），是高伸缩性系统的[首要的](http://highscalability.com/blog/2009/10/7/how-to-avoid-the-top-5-scale-out-pitfalls.html) [设计](http://highscalability.com/blog/2009/8/11/13-scalability-best-practices.html) [原则](http://highscalability.com/blog/2009/5/8/eight-best-practices-for-building-scalable-systems.html)，对Java来说，这意味着[JMS](http://java.sun.com/products/jms/)，然后又意味着[ActiveMQ](http://activemq.apache.org/)。但是[我如何高效的使用JMS呢](http://activemq.apache.org/how-do-i-use-jms-efficiently.html)？一个人很有可能会不知所措，在谈论容器、框架、和一堆选项时。那么让我们分开来探讨下。

## 框架

ActiveMQ文档中提及两个框架：[Camel](http://camel.apache.org/)和[Spring](http://www.springsource.org/about)。那么要做决定就取决于简单性和功能性的对比。Camel支持大量的[企业集成模式](http://en.wikipedia.org/wiki/Enterprise_Integration_Patterns)（Enterprise Integration Patterns），它可以大大简化集成组件间的大量服务和复杂的消息流。如果你的系统需要这样的功能，它当然是非常好的选择。然而，如果你寻找简单性，仅仅支持基本的最佳实践，那么Spring是好的选择。

## JCA (使用它或放弃它)

 

阅读ActiveMQ的[Spring支持](http://activemq.apache.org/spring-support.html)时，开发者立刻被介绍了JCA容器和ActiveMQ很多的代理和[适配器](http://activemq.apache.org/resource-adapter.html)选项的概念。然而这些都不适应。JCA是[EJB](http://java.sun.com/products/ejb/)规范的一部分，对于大部分EJB规范，Spring都没有提供很好的支持。这时，就提到了[Jencks](http://docs.codehaus.org/display/JCA/Home)，”为Spring提供的轻量级JCA容器”，它可以作为ActiveMQ的[JCA容器](http://activemq.apache.org/jca-container.html)。 乍看上去，这是个非常好的解决方案，但是我在这里告诉你不要这样做。Jencks最后更新时间是2007年1月。那时ActiveMQ的版本是 4.1x，Spring的版本是2.0.x，但是时间过了很多，事情也变化了很大。甚至是试图从Maven库中获取ActiveMQ4.1的依赖包 Jencks都会失败，因为它已经不存在了。简单的事实是有更好和更简单的方式来缓存资源。

## 发送消息

Spring消息发送的核心架构是[JmsTemplate](http://static.springsource.org/spring/docs/2.5.6/api/org/springframework/jms/core/JmsTemplate.html)。在传统的Spring模板方式中，JmsTemplate隔离了像打开、关闭Session和Producer的繁琐操作，因此应用开发人员仅仅需要关注实际的业务逻辑。然而ActiveMQ快速的指出了[JmsTemplate gotchas](http://activemq.apache.org/jmstemplate-gotchas.html)，大多是因为JmsTemplate被设计在每次调用时都打开和关闭session及producer。JmsTemplate损害了ActiveMQ的[PooledConnectionFactory](http://activemq.apache.org/maven/activemq-pool/apidocs/org/apache/activemq/pool/PooledConnectionFactory.html)对session和消息producer的缓存机制而带来的性能提升。然而，这个太过时了。从Spring2.5.3开始，它开始提供自己的[CachingConnectionFactory](http://static.springsource.org/spring/docs/2.5.6/api/org/springframework/jms/connection/CachingConnectionFactory.html)，我相信该类在缓存方面更加强大。然而，这里有一个点需要注意。默认情况下，CachingConnectionFactory只缓存一个session，在它的JavaDoc中，它[声明对于低并发情况下这是足够的](http://static.springsource.org/spring/docs/2.5.6/api/org/springframework/jms/connection/CachingConnectionFactory.html#setSessionCacheSize%28int%29)。与之相反，PooledConnectionFactory的[默认值是500](http://www.docjar.com/html/api/org/apache/activemq/pool/PooledConnectionFactory.java.html)。这些设置，在很多情况下，需要亲自去测试并验证。我将其设置为100，对我来说还是很不错。

## 接收消息

可能你已经注意了，[JmsTemplate gotchas](http://activemq.apache.org/jmstemplate-gotchas.html)强 烈的不建议你使用JmsTemplate的receive()调用，同样也是因为没有session和consumer的池机制。更多的原因是在 JmsTemplate上的所有调用都是同步的，这意味着调用线程需要被阻塞，直到方法返回。这在使用JmsTemplate发送消息时，没有任何问题， 因为该方法几乎是立即返回。然而，当调用receive方法时，线程将阻塞，直到接收到一个消息为止，这对性能影响很大。不幸的是，[JmsTemplate gotchas](http://activemq.apache.org/jmstemplate-gotchas.html)和[Spring支持文档](http://activemq.apache.org/spring-support.html)中都没有对该问题提供简单的解决方案。实际上，它们均提倡使用[Jencks](http://docs.codehaus.org/display/JCA/Home)，我们之前已经说过。实际的解决方案，使用[DefaultMessageListenerContainer](http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/jms/listener/DefaultMessageListenerContainer.html)，已经写在了[how do I use JMS efficiently](http://activemq.apache.org/how-do-i-use-jms-efficiently.html)文 档中。DefaultMessageListenerContainer允许异步接收消息并缓存session和消息consumer。更有趣的 是，DefaultMessageListenerContainer可以根据消息数量动态的增加或缩减监听器的数量。简而言之，我们可以完全忽视 JCA。

合并起来

### Spring Context配置文件

&lt;? xml version ="1.0" encoding ="UTF-8"?&gt;  
&lt;beansxmlns="http://www.springframework.org/schema/beans"  
xmlns:amq="http://activemq.apache.org/schema/core"xmlns:jms="http://www.springframework.org/schema/jms"  
xmlns:context="http://www.springframework.org/schema/context"  
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-2.5.xsd  
http://activemq.apache.org/schema/core http://activemq.apache.org/schema/core/activemq-core-5.2.0.xsd  
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd  
http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms-2.5.xsd"&gt;  
&lt;!-- enables annotation based configuration --&gt;  
&lt;context:annotation-config/&gt;  
&lt;!-- scans for annotated classes in the com.company package --&gt;  
&lt;context:component-scanbase-package="net.javasight"/&gt;  
&lt;!--  
allows for ${} replacement in the spring xml configuration from the  
system.properties file on the classpath  
\--&gt;  
&lt;context:property-placeholderlocation="classpath:system.properties"/&gt;  
&lt;!-- creates an activemq connection factory using the amq namespace --&gt;  
&lt;amq:connectionFactoryid="amqConnectionFactory"  
brokerURL="${jms.url}"userName="${jms.username}"password="${jms.password}"/&gt;  
&lt;!--  
CachingConnectionFactory Definition, sessionCacheSize property is the  
number of sessions to cache  
\--&gt;  
&lt;beanid="connectionFactory"  
class="org.springframework.jms.connection.CachingConnectionFactory"&gt;  
&lt;constructor-argref="amqConnectionFactory"/&gt;  
&lt;propertyname="exceptionListener"ref="jmsExceptionListener"/&gt;  
&lt;propertyname="sessionCacheSize"value="100"/&gt;  
&lt;/bean&gt;  
&lt;!-- JmsTemplate Definition --&gt;  
&lt;beanid="jmsTemplate"class="org.springframework.jms.core.JmsTemplate"&gt;  
&lt;constructor-argref="connectionFactory"/&gt;  
&lt;/bean&gt;  
&lt;!--  
listener container definition using the jms namespace, concurrency is  
the max number of concurrent listeners that can be started  
\--&gt;  
&lt;jms:listener-containerconcurrency="10"&gt;  
&lt;jms:listenerid="QueueListener"destination="Queue.Name"  
ref="queueListener"/&gt;  
&lt;/jms:listener-container&gt;  
&lt;/beans&gt;

这里有两点需要注意。首先，我添加了amq和jms的命名空间。第二，我使用了Spring2.5的[基于注解的配置](http://static.springsource.org/spring/docs/2.5.x/reference/beans.html#beans-annotation-config)。通过使用基于注解的配置，我可以简单的添加[@Component](http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/stereotype/Component.html)注解到我的Java类上，而不是使用XML文件显式的在spring配置文件中定义它们。另外，我可以在我的构造方法中使用[@Autowired](http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/beans/factory/annotation/Autowired.html)来将像JmsTemplate这样的对象注入到我的对象中。

### QueueSender

```
package net.javasight;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Component;

@Component
publicclassQueueSender{
privatefinalJmsTemplate jmsTemplate;
@Autowired
publicQueueSender(finalJmsTemplate jmsTemplate){
this.jmsTemplate = jmsTemplate;
}

publicvoid send(finalString message){
                jmsTemplate.convertAndSend("Queue.Name", message);
}
}
```

 

### Queue Listener

package net.javasight;

import javax.jms.JMSException;  
import javax.jms.Message;  
import javax.jms.MessageListener;  
import javax.jms.TextMessage;  
import org.springframework.stereotype.Component;

@Component  
publicclassQueueListenerimplementsMessageListener{  
publicvoid onMessage(finalMessage message){  
if(message instanceofTextMessage){  
finalTextMessage textMessage =(TextMessage) message;  
try{  
System.out.println(textMessage.getText());  
}catch(finalJMSException e){  
e.printStackTrace();  
}  
}  
}  
}

 

### JmsExceptionListener

package net.javasight;

import javax.jms.ExceptionListener;  
import javax.jms.JMSException;  
import org.springframework.stereotype.Component;

@Component  
publicclassJmsExceptionListenerimplementsExceptionListener{

publicvoid onException(finalJMSException e){  
e.printStackTrace();  
}  
}