在实际的项目中如果使用原生的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整合的更多相关文章

  1. Spring和ActiveMQ整合的完整实例

     Spring和ActiveMQ整合的完整实例 前言 这篇博文,我们基于Spring+JMS+ActiveMQ+Tomcat,做一个Spring4.1.0和ActiveMQ5.11.1整合实例,实现了 ...

  2. 深入浅出JMS(四)--Spring和ActiveMQ整合的完整实例

    第一篇博文深入浅出JMS(一)–JMS基本概念,我们介绍了JMS的两种消息模型:点对点和发布订阅模型,以及消息被消费的两个方式:同步和异步,JMS编程模型的对象,最后说了JMS的优点. 第二篇博文深入 ...

  3. JMS【四】--Spring和ActiveMQ整合的完整实例

    第一篇博文JMS[一]--JMS基本概念,我们介绍了JMS的两种消息模型:点对点和发布订阅模型,以及消息被消费的两个方式:同步和异步,JMS编程模型的对象,最后说了JMS的优点. 第二篇博文JMS[二 ...

  4. Spring JMS ActiveMQ整合(转)

    转载自:http://my.oschina.net/xiaoxishan/blog/381209#comment-list ActiveMQ学习笔记(四)http://my.oschina.net/x ...

  5. Spring mvc4 + ActiveMQ 整合

    一.配置部分 二.代码部分 三.页面部分 四.Controller控制器 五.效果展示 六.加入监听器 七.最最重要的,别忘了打赏 一.配置部分 ActiveMQ的安装这就不说了,很简单, 这个例子采 ...

  6. 学习ActiveMQ(四):spring与ActiveMQ整合

    在上一篇中已经怎么使用activemq的api来实现消息的发送接收了,但是在实际的开发过程中,我们很少使用activemq直接上去使用,因为我们每次都要创建连接工厂,创建连接,创建session... ...

  7. Spring mvc4 + ActiveMQ 整合【什么框架与什么框架的整合搜索】

    一.配置部分 二.代码部分 三.页面部分 四.Controller控制器 五.效果展示 六.加入监听器 七.最最重要的,别忘了打赏 一.配置部分 ActiveMQ的安装这就不说了,很简单, 这个例子采 ...

  8. ActiveMQ整合spring、同步索引库

    1.   Activemq整合spring 1.1. 使用方法 第一步:引用相关的jar包. <dependency> <groupId>org.springframework ...

  9. JAVAEE——宜立方商城09:Activemq整合spring的应用场景、添加商品同步索引库、商品详情页面动态展示与使用缓存

    1. 学习计划 1.Activemq整合spring的应用场景 2.添加商品同步索引库 3.商品详情页面动态展示 4.展示详情页面使用缓存 2. Activemq整合spring 2.1. 使用方法 ...

随机推荐

  1. kafka与传统的消息中间件对比

    RabbitMQ和kafka从几个角度简单的对比 业界对于消息的传递有多种方案和产品,本文就比较有代表性的两个MQ(rabbitMQ,kafka)进行阐述和做简单的对比, 在应用场景方面, Rabbi ...

  2. 基于NPOI的报表引擎——ExcelReport

    前言 其实现在说ExcelReport是报表引擎还为时尚早,但该组件我既然要决心维护下去,这便算是初衷吧! 1.现在,ExcelReport能为你做什么呢? 如果,你有导出数据到Excel的需求,Ex ...

  3. PCM数据格式,多少字节算一帧

    转自:http://blog.chinaunix.net/uid-9185047-id-3327302.html Somehow i remember that normally 2048 sampl ...

  4. HTML5编码规范

    为每个 HTML 页面的第一行添加标准模式(standard mode)的声明,这样能够确保在每个浏览器中拥有一致的展现. 用两个空格来代替制表符(tab) -- 这是唯一能保证在所有环境下获得一致展 ...

  5. 管理node的版本

    检查当前node的版本 node -v 清除npm cache sudo npm cache clean -f 安装n模块 sudo npm install -g n 切换到别的版本,比如 v4.4. ...

  6. T-SQL 基础学习 01

    --新建数据库 create database Studentdb go --使用数据库 use Studentdb go --新建表 create table Username ( StudentN ...

  7. CSS3动画效果-7.13

    例如: <body> <div class="div1"></div> </body> CSS: @keyframes myfirs ...

  8. Mysql与PostgreSql数据库学习笔记---打酱油的日子

    mysql 从最基础的数据引擎,到进程结构,都不能支持数据版本.导致其职能阻塞“并发”,不支持最基本的事务,innodb达不到基本事务要求,任何写数据,都导致整个表锁住.充其量只能算是一个玩具,或者说 ...

  9. nginx 直接在配置文章中设置日志分割

    直接在nginx配置文件中,配置日志循环,而不需使用logrotate或配置cron任务.需要使用到$time_iso8601 内嵌变量来获取时间.$time_iso8601格式如下:2015-08- ...

  10. HDU 3038 How Many Answers Are Wrong(种类并查集)

    题目链接 食物链类似的题,主要是在于转化,a-b的和为s,转换为b比a-1大s.然后并查集存 此节点到根的差. 假如x的根为a,y的根为b: b - y = rank[y] a - x = rank[ ...