转载自:http://my.oschina.net/xiaoxishan/blog/381209#comment-list

ActiveMQ学习笔记(四)http://my.oschina.net/xiaoxishan/blog/380446 中 记录了如何使用原生的方式从ActiveMQ中收发消息。可以看出,每次收发消息都要写许多重复的代码,Spring 为我们提供了更为方便的方式,这就是Spring JMS。我们通过一个例子展开讲述。包括队列、主题消息的收发相关的Spring配置、代码、测试。

本例中,消息的收发都写在了一个工程里。

1.使用maven管理依赖包

<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-all</artifactId>
<version>5.11.0</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jms</artifactId>
<version>4.1.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.1.4.RELEASE</version>
</dependency>
</dependencies>

2.队列消息的收发

2.1Spring配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
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.xsd"> <!-- 配置JMS连接工厂 -->
<bean id="connectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
<property name="brokerURL" value="failover:(tcp://localhost:61616)" />
</bean> <!-- 定义消息队列(Queue) -->
<bean id="queueDestination" class="org.apache.activemq.command.ActiveMQQueue">
<!-- 设置消息队列的名字 -->
<constructor-arg>
<value>queue1</value>
</constructor-arg>
</bean> <!-- 配置JMS模板(Queue),Spring提供的JMS工具类,它发送、接收消息。 -->
<bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
<property name="connectionFactory" ref="connectionFactory" />
<property name="defaultDestination" ref="queueDestination" />
<property name="receiveTimeout" value="10000" />
</bean> <!--queue消息生产者 -->
<bean id="producerService" class="guo.examples.mq02.queue.ProducerServiceImpl">
<property name="jmsTemplate" ref="jmsTemplate"></property>
</bean> <!--queue消息消费者 -->
<bean id="consumerService" class="guo.examples.mq02.queue.ConsumerServiceImpl">
<property name="jmsTemplate" ref="jmsTemplate"></property>
</bean>

2.2消息生产者代码

从下面的代码可以出,使用Spring JMS,可以减少重复代码(接口类ProducerService代码省略)。

package guo.examples.mq02.queue;

import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session; import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator; public class ProducerServiceImpl implements ProducerService { private JmsTemplate jmsTemplate; /**
* 向指定队列发送消息
*/
public void sendMessage(Destination destination, final String msg) {
System.out.println("向队列" + destination.toString() + "发送了消息------------" + msg);
jmsTemplate.send(destination, new MessageCreator() {
public Message createMessage(Session session) throws JMSException {
return session.createTextMessage(msg);
}
});
} /**
* 向默认队列发送消息
*/
public void sendMessage(final String msg) {
String destination = jmsTemplate.getDefaultDestination().toString();
System.out.println("向队列" +destination+ "发送了消息------------" + msg);
jmsTemplate.send(new MessageCreator() {
public Message createMessage(Session session) throws JMSException {
return session.createTextMessage(msg);
}
}); } public void setJmsTemplate(JmsTemplate jmsTemplate) {
this.jmsTemplate = jmsTemplate;
} }

2.3消息消费者代码

package guo.examples.mq02.queue;

import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.TextMessage; import org.springframework.jms.core.JmsTemplate; public class ConsumerServiceImpl implements ConsumerService { private JmsTemplate jmsTemplate; /**
* 接受消息
*/
public void receive(Destination destination) {
TextMessage tm = (TextMessage) jmsTemplate.receive(destination);
try {
System.out.println("从队列" + destination.toString() + "收到了消息:\t"
+ tm.getText());
} catch (JMSException e) {
e.printStackTrace();
}
} public void setJmsTemplate(JmsTemplate jmsTemplate) {
this.jmsTemplate = jmsTemplate;
} }

2.4队列消息监听

接受消息的时候,可以不用2.3节中的方式,Spring JMS同样提供了消息监听的模式,下面给出对应的配置和代码。

Spring配置

<!-- 定义消息队列(Queue),我们监听一个新的队列,queue2 -->
<bean id="queueDestination2" class="org.apache.activemq.command.ActiveMQQueue">
<!-- 设置消息队列的名字 -->
<constructor-arg>
<value>queue2</value>
</constructor-arg>
</bean> <!-- 配置消息队列监听者(Queue),代码下面给出,只有一个onMessage方法 -->
<bean id="queueMessageListener" class="guo.examples.mq02.queue.QueueMessageListener" /> <!-- 消息监听容器(Queue),配置连接工厂,监听的队列是queue2,监听器是上面定义的监听器 -->
<bean id="jmsContainer"
class="org.springframework.jms.listener.DefaultMessageListenerContainer">
<property name="connectionFactory" ref="connectionFactory" />
<property name="destination" ref="queueDestination2" />
<property name="messageListener" ref="queueMessageListener" />
</bean>

监听类代码

package guo.examples.mq02.queue;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage; public class QueueMessageListener implements MessageListener {
//当收到消息时,自动调用该方法。
public void onMessage(Message message) {
TextMessage tm = (TextMessage) message;
try {
System.out.println("ConsumerMessageListener收到了文本消息:\t"
+ tm.getText());
} catch (JMSException e) {
e.printStackTrace();
}
} }

3.主题消息收发

在使用Spring JMS的时候,主题(Topic)和队列消息的主要差异体现在JmsTemplate中"pubSubDomain"是否设置为True。如果为True,则是Topic;如果是false或者默认,则是queue。

<property name="pubSubDomain" value="true" />

3.1Spring配置

<!-- 定义消息主题(Topic) -->
<bean id="topicDestination" class="org.apache.activemq.command.ActiveMQTopic">
<constructor-arg>
<value>guo_topic</value>
</constructor-arg>
</bean>
<!-- 配置JMS模板(Topic),pubSubDomain="true"-->
<bean id="topicJmsTemplate" class="org.springframework.jms.core.JmsTemplate">
<property name="connectionFactory" ref="connectionFactory" />
<property name="defaultDestination" ref="topicDestination" />
<property name="pubSubDomain" value="true" />
<property name="receiveTimeout" value="10000" />
</bean>
<!--topic消息发布者 -->
<bean id="topicProvider" class="guo.examples.mq02.topic.TopicProvider">
<property name="topicJmsTemplate" ref="topicJmsTemplate"></property>
</bean>
<!-- 消息主题监听者 和 主题监听容器 可以配置多个,即多个订阅者 -->
<!-- 消息主题监听者(Topic) -->
<bean id="topicMessageListener" class="guo.examples.mq02.topic.TopicMessageListener" />
<!-- 主题监听容器 (Topic) -->
<bean id="topicJmsContainer"
class="org.springframework.jms.listener.DefaultMessageListenerContainer">
<property name="connectionFactory" ref="connectionFactory" />
<property name="destination" ref="topicDestination" />
<property name="messageListener" ref="topicMessageListener" />
</bean>

3.2消息发布者

package guo.examples.mq02.topic;

import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session; import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator; public class TopicProvider { private JmsTemplate topicJmsTemplate; /**
* 向指定的topic发布消息
*
* @param topic
* @param msg
*/
public void publish(final Destination topic, final String msg) { topicJmsTemplate.send(topic, new MessageCreator() {
public Message createMessage(Session session) throws JMSException {
System.out.println("topic name 是" + topic.toString()
+ ",发布消息内容为:\t" + msg);
return session.createTextMessage(msg);
}
});
} public void setTopicJmsTemplate(JmsTemplate topicJmsTemplate) {
this.topicJmsTemplate = topicJmsTemplate;
} }

3.3消息订阅者(监听)

package guo.examples.mq02.topic;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;
/**
*和队列监听的代码一样。
*/
public class TopicMessageListener implements MessageListener { public void onMessage(Message message) {
TextMessage tm = (TextMessage) message;
try {
System.out.println("TopicMessageListener \t" + tm.getText());
} catch (JMSException e) {
e.printStackTrace();
}
} }

4.测试

4.1 测试代码

package guo.examples.mq02;

import javax.jms.Destination;

import guo.examples.mq02.queue.ConsumerService;
import guo.examples.mq02.queue.ProducerService;
import guo.examples.mq02.topic.TopicProvider; import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /**
* 测试Spring JMS
*
* 1.测试生产者发送消息
*
* 2. 测试消费者接受消息
*
* 3. 测试消息监听
*
* 4.测试主题监听
*
*/
@RunWith(SpringJUnit4ClassRunner.class)
// ApplicationContext context = new
// ClassPathXmlApplicationContext("applicationContext.xml");
@ContextConfiguration("/applicationContext.xml")
public class SpringJmsTest { /**
* 队列名queue1
*/
@Autowired
private Destination queueDestination; /**
* 队列名queue2
*/
@Autowired
private Destination queueDestination2; /**
* 主题 guo_topic
*/
@Autowired
@Qualifier("topicDestination")
private Destination topic; /**
* 主题消息发布者
*/
@Autowired
private TopicProvider topicProvider; /**
* 队列消息生产者
*/
@Autowired
@Qualifier("producerService")
private ProducerService producer; /**
* 队列消息生产者
*/
@Autowired
@Qualifier("consumerService")
private ConsumerService consumer; /**
* 测试生产者向queue1发送消息
*/
@Test
public void testProduce() {
String msg = "Hello world!";
producer.sendMessage(msg);
} /**
* 测试消费者从queue1接受消息
*/
@Test
public void testConsume() {
consumer.receive(queueDestination);
} /**
* 测试消息监听
*
* 1.生产者向队列queue2发送消息
*
* 2.ConsumerMessageListener监听队列,并消费消息
*/
@Test
public void testSend() {
producer.sendMessage(queueDestination2, "Hello China~~~~~~~~~~~~~~~");
} /**
* 测试主题监听
*
* 1.生产者向主题发布消息
*
* 2.ConsumerMessageListener监听主题,并消费消息
*/
@Test
public void testTopic() throws Exception {
topicProvider.publish(topic, "Hello T-To-Top-Topi-Topic!");
} }

4.2 测试结果

topic name 是topic://guo_topic,发布消息内容为:    Hello T-To-Top-Topi-Topic!
TopicMessageListener Hello T-To-Top-Topi-Topic!
向队列queue://queue2发送了消息------------Hello China~~~~~~~~~~~~~~~
ConsumerMessageListener收到了文本消息: Hello China~~~~~~~~~~~~~~~
向队列queue://queue1发送了消息------------Hello world!
从队列queue://queue1收到了消息: Hello world!

5.代码地址

http://pan.baidu.com/s/1gdvPpWf

 

Spring JMS ActiveMQ整合(转)的更多相关文章

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

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

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

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

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

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

  4. Spring整合ActiveMQ:spring+JMS+ActiveMQ+Tomcat

    一.目录结构 相关jar包 二.关键配置activmq.xml <?xml version="1.0" encoding="UTF-8"?> < ...

  5. Spring与ActiveMQ整合

    Spring提供了对JMS的支持,需要添加Spring支持jms的包,如下: <dependency> <groupId>org.springframework</gro ...

  6. Spring mvc4 + ActiveMQ 整合

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

  7. Spring + JMS + ActiveMQ实现简单的消息队列(监听器异步实现)

    首先声明:以下内容均是在网上找别人的博客综合学习而成的,可能会发现某些代码与其他博主的相同,由于参考的文章比较多,这里对你们表示感谢,就不一一列举,如果有侵权的地方,请通知我,我可以把该文章删除. 1 ...

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

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

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

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

随机推荐

  1. A simple Snippet in ST2

    Reference: http://web-design-weekly.com/2012/07/03/snippets-in-sublime-text-2/ A sample - cofirm (To ...

  2. 【AngularJS】—— 4 表达式

    前面了解了AngularJS的基本用法,这里就跟着PDF一起学习下表达式的相关内容. 在AngularJS中的表达式,与js中并不完全相同. 首先它的表达式要放在{{}}才能使用,其次相对于javas ...

  3. express 框架之 路由与中间件

    1.  什么是router路径,什么是middleware? 我们输入www.baidu.com 来访问百度的主页,浏览器会自动转换为 http://www.baidu.com:80/(省略一些参数) ...

  4. resin

    http://blog.csdn.net/sea0x/article/details/6097531 resin 启动: resin 配置文件摘取: <server-default> &l ...

  5. tcp/ip协议栈调用关系图

    最近阅读了tcp/ip详解卷2,总结一下整个发送过程和接收过程 sendmsg \/ sendit \/ sosend(这一步将数据从用户空间拷贝到内核空间,并且会在这一步判断发送缓存空间是否充足,是 ...

  6. PHP基础 之 基本数据类型练习

    <h3>PHP基础练习</h3> <?php echo "<h4>常量</h4>"; //定义:一般大写,使用下划线间隔 de ...

  7. 文字的多列布局--column

  8. InnoDB为什么要使用auto_Increment

    在Mysql表设计中,通常会使用一个与业务无关的自增列做为主键.这是因为Mysql默认使用B-Tree索引,你可以简单理解为"排好序的快速查找结构".如下是一个B-Tree的结构图 ...

  9. 爆料喽!!!开源日志库Logger的剖析分析

    导读 Logger类提供了多种方法来处理日志活动.上一篇介绍了开源日志库Logger的使用,今天我主要来分析Logger实现的原理. 库的整体架构图 详细剖析 我们从使用的角度来对Logger库抽茧剥 ...

  10. UNITY3d在移动设备上的一些优化实战(一)-概述

    转自:UNITY3d在移动设备上的一些优化实战(一)-概述 http://blog.csdn.net/leonwei/article/details/39233921 项目进入了中期之后,就需要对程序 ...