Spring与ActiveMQ整合
在实际的项目中如果使用原生的ActiveMQ API开发会比较麻烦,因为需要创建连接工厂,创建连接等,我们应该使用一个模板来做这些繁琐的事情,Spring帮我们做了!
Spring提供了对JMS的支持,需要添加Spring支持jms的包,如下:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jms</artifactId>
<version>4.0.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-pool</artifactId>
<version>5.9.0</version>
</dependency>
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-all</artifactId>
<version>5.9.0</version>
</dependency>
在spring-amq.xml中配置JmsTemplate(这样的配置没啥问题,在实际的项目中就是这样配置的)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"> <context:component-scan base-package="com.winner.spring"/> <bean id="jmsFactory" class="org.apache.activemq.pool.PooledConnectionFactory"
destroy-method="stop">
<property name="connectionFactory">
<bean class="org.apache.activemq.ActiveMQConnectionFactory">
<property name="brokerURL">
<value>tcp://192.168.0.129:61616</value>
</property>
</bean>
</property>
<property name="maxConnections" value="100"></property>
</bean> <!--使用缓存可以提升效率-->
<bean id="cachingConnectionFactory" class="org.springframework.jms.connection.CachingConnectionFactory">
<property name="targetConnectionFactory" ref="jmsFactory"/>
<property name="sessionCacheSize" value="1"/>
</bean> <bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
<property name="connectionFactory" ref="cachingConnectionFactory"/>
<property name="messageConverter">
<bean class="org.springframework.jms.support.converter.SimpleMessageConverter"/>
</property>
</bean> <!--测试Queue,队列的名字是spring-queue-->
<bean id="destinationQueue" class="org.apache.activemq.command.ActiveMQQueue">
<!--<constructor-arg index="0" value="spring-queue"/>-->
<constructor-arg name="name" value="spring-queue"/>
</bean> <!--测试Topic-->
<bean id="destinationTopic" class="org.apache.activemq.command.ActiveMQTopic">
<constructor-arg index="0" value="spring-topic"/>
</bean> </beans>
生产者
@Service
public class AMQSenderServiceImpl implements AmqSenderService { private static final Logger logger = LoggerFactory.getLogger(AMQSenderServiceImpl.class); @Resource(name = "jmsTemplate")
private JmsTemplate jmsTemplate; //目的地队列的明证,我们要向这个队列发送消息
@Resource(name = "destinationQueue")
private Destination destination; //向特定的队列发送消息
@Override
public void sendMsg(MqParamDto mqParamDto) {
final String msg = JSON.toJSONString(mqParamDto);
try {
logger.info("将要向队列{}发送的消息msg:{}", destination, msg);
jmsTemplate.send(destination, new MessageCreator() {
@Override
public Message createMessage(Session session) throws JMSException {
return session.createTextMessage(msg);
}
}); } catch (Exception ex) {
logger.error("向队列{}发送消息失败,消息为:{}", destination, msg);
} }
}
运行结果:


如果是Topic的话就换一下,下面的spring-topic是主题的名字。
<bean id="destinationTopic" class="org.apache.activemq.command.ActiveMQTopic">
<constructor-arg index="0" value="spring-topic" />
</bean>
其他不用改!
如果想要在Spring中配置消费者的话,就不需要再启动接收的客户端了,这样在测试的时候可以不需要写消费者的代码,因为我们要么是生产者要么是消费者!
可以通过配置一个listener来实现,实际项目中采用的是这种方式
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"> <bean id="jmsFactory" class="org.apache.activemq.pool.PooledConnectionFactory"
destroy-method="stop">
<property name="connectionFactory">
<bean class="org.apache.activemq.ActiveMQConnectionFactory">
<property name="brokerURL">
<value>tcp://192.168.0.129:61616</value>
</property>
</bean>
</property>
<property name="maxConnections" value="100"></property>
</bean> <!--使用缓存可以提升效率-->
<bean id="cachingConnectionFactory"
class="org.springframework.jms.connection.CachingConnectionFactory">
<property name="targetConnectionFactory" ref="jmsFactory"/>
<property name="sessionCacheSize" value="1"/>
</bean> <!--测试Queue,队列的名字是spring-queue-->
<bean id="destinationQueue" class="org.apache.activemq.command.ActiveMQQueue">
<constructor-arg index="0" value="spring-queue"/>
</bean> <!--测试Topic-->
<bean id="destinationTopic" class="org.apache.activemq.command.ActiveMQTopic">
<constructor-arg index="0" value="spring-topic"/>
</bean> <bean id="jmsContainer"
class="org.springframework.jms.listener.DefaultMessageListenerContainer">
<property name="connectionFactory" ref="cachingConnectionFactory"/>
<property name="destination" ref="destinationQueue"/>
<property name="messageListener" ref="messageListener"/>
</bean> <!--消息监听器-->
<bean id="messageListener" class="com.winner.spring.MyMessageListener">
</bean> </beans>
监听器:
public class MyMessageListener implements MessageListener {
@Override
public void onMessage(Message msg) {
if (msg instanceof TextMessage) {
try {
TextMessage txtMsg = (TextMessage) msg;
String message = txtMsg.getText();
//实际项目中拿到String类型的message(通常是JSON字符串)之后,
//会进行反序列化成对象,做进一步的处理
System.out.println("receive txt msg===" + message);
} catch (JMSException e) {
throw new RuntimeException(e);
}
} else {
throw new IllegalArgumentException("Message must be of type TextMessage");
}
}
}
不需要写消费者的代码就可以知道消息有没有推送成功

ActiveMQ结合Spring开发最佳实践和建议:
1:Camel框架支持大量的企业集成模式,可以大大简化集成组件间的大量服务和复杂的消息流。而Spring框架更注重简单性,仅仅支持基本的最佳实践。
2:Spring消息发送的核心架构是JmsTemplate,隔离了像打开、关闭Session和Producer的繁琐操作,因此应用开发人员仅仅需要关注实际的业务逻辑。但是
JmsTemplate损害了ActiveMQ的PooledConnectionFactory对session和消息producer的缓存机制而带来的性能提升。
3:新的Spring里面,可以设置org.springframework.jms.connection.CachingConnectionFactory的sessionCacheSize,或者干脆使用ActiveMQ的PooledConnectionFactory
4:不建议使用JmsTemplate的receive()调用,因为在JmsTemplate上的所有调用都是同步的,这意味着调用线程需要被阻塞,直到方法返回,这对性能影响很大
5:请使用DefaultMessageListenerContainer,它允许异步接收消息并缓存session和消息consumer,而且还可以根据消息数量动态的增加或缩减监听器的数量
Spring与ActiveMQ整合的更多相关文章
- Spring和ActiveMQ整合的完整实例
Spring和ActiveMQ整合的完整实例 前言 这篇博文,我们基于Spring+JMS+ActiveMQ+Tomcat,做一个Spring4.1.0和ActiveMQ5.11.1整合实例,实现了 ...
- 深入浅出JMS(四)--Spring和ActiveMQ整合的完整实例
第一篇博文深入浅出JMS(一)–JMS基本概念,我们介绍了JMS的两种消息模型:点对点和发布订阅模型,以及消息被消费的两个方式:同步和异步,JMS编程模型的对象,最后说了JMS的优点. 第二篇博文深入 ...
- JMS【四】--Spring和ActiveMQ整合的完整实例
第一篇博文JMS[一]--JMS基本概念,我们介绍了JMS的两种消息模型:点对点和发布订阅模型,以及消息被消费的两个方式:同步和异步,JMS编程模型的对象,最后说了JMS的优点. 第二篇博文JMS[二 ...
- Spring JMS ActiveMQ整合(转)
转载自:http://my.oschina.net/xiaoxishan/blog/381209#comment-list ActiveMQ学习笔记(四)http://my.oschina.net/x ...
- Spring mvc4 + ActiveMQ 整合
一.配置部分 二.代码部分 三.页面部分 四.Controller控制器 五.效果展示 六.加入监听器 七.最最重要的,别忘了打赏 一.配置部分 ActiveMQ的安装这就不说了,很简单, 这个例子采 ...
- 学习ActiveMQ(四):spring与ActiveMQ整合
在上一篇中已经怎么使用activemq的api来实现消息的发送接收了,但是在实际的开发过程中,我们很少使用activemq直接上去使用,因为我们每次都要创建连接工厂,创建连接,创建session... ...
- Spring mvc4 + ActiveMQ 整合【什么框架与什么框架的整合搜索】
一.配置部分 二.代码部分 三.页面部分 四.Controller控制器 五.效果展示 六.加入监听器 七.最最重要的,别忘了打赏 一.配置部分 ActiveMQ的安装这就不说了,很简单, 这个例子采 ...
- ActiveMQ整合spring、同步索引库
1. Activemq整合spring 1.1. 使用方法 第一步:引用相关的jar包. <dependency> <groupId>org.springframework ...
- JAVAEE——宜立方商城09:Activemq整合spring的应用场景、添加商品同步索引库、商品详情页面动态展示与使用缓存
1. 学习计划 1.Activemq整合spring的应用场景 2.添加商品同步索引库 3.商品详情页面动态展示 4.展示详情页面使用缓存 2. Activemq整合spring 2.1. 使用方法 ...
随机推荐
- hdu 1358 Period
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1358 思路:Next数组的用法,在第i个位置上如果有i%(i-Next[i])==0的话最小循环节就是 ...
- 【Java EE 学习 15】【自定义数据库连接池之动态代理的使用】
一.动态代理的作用 使用动态代理可以拦截一个对象某个方法的执行,并执行自定义的方法,其本质是反射 优点:灵活 缺点:由于其本质是反射,所以执行速度相对要慢一些 二.数据库连接池设计思想 1.为什么要使 ...
- linux 限制root SSH登陆和限制su
linux 限制root用户SSH登录: 1.修改SSHD服务的配置文件/etc/ssh/sshd_config 将#PermitRootLogin yes 改为PermitRootLogi ...
- 【Unity3d游戏开发】UGUI插件入门之游戏菜单
ugui是unity4.6开始加入的一个新的ui系统,非常强大,下面我们将通过一系列博客的方式一起来学习一下ugui的使用.本篇博客会介绍如何使用ugui制作一个游戏菜单,并且了解如何让物体与ugui ...
- JDBC连接数据库(数据源的方式)
在tomcat安装目录下的context.xml文件中配置DataSource <Resource name="jdbc/news"(JNDI的名字,news是数据库的实例名 ...
- Python中的list和tuple
list使用方括号[ ]表示: >>> classmates = ['Michael', 'Bob', 'Tracy'] >>> classmates ['Mi ...
- 关于 error: Operation is not valid due to the current state of the object。
今天碰到一个特别的异常. Operation is not valid due to the current state of the object. at System.Web.HttpValueC ...
- MySQL:索引工作原理
索引查找:通过索引键找到索引的叶子节点,再通过叶子节点的标记快速找到表中对应的行数据,再返回指定的列 索引找查是通过索引键定先位到一块局部区域,再开始扫描匹配的数据的. 为什么需要索引(Why is ...
- gong server
宫 server mac os 系统 vpn 202.39.176.66 funmobigtmvpn 密码 funmobi!@ 安装 eclipse 安装mysql 1 配置 ...
- 关于HTML Table标签的边框问题总结
要想td与td间没有距离需要设置如下属性: <table id="table" cellpadding="2" cellspacing="0&q ...