ActiveMQ消息队列从入门到实践(4)—使用Spring JMS收发消息
Java消息服务(Java Message Service ,JMS)是一个Java标准,定义了使用消息代理的通用API 。在JMS出现之前,每个消息代理都有私有的API,这就使得不同代理之间的消息代码很难通用。但是借助JMS,所有遵从规范的实现都使用通用的接口,这就类似于JDBC为数据库操作提供了通用的接口一样。
Spring通过基于模板的抽象为JMS功能提供了支持,这个模板也就是JmsTemplate。使用JmsTemplate ,能够非常容易地在消息生产方发送队列和主题消息,在消费消息的那一方,也能够非常容易地接收这些消息。
Queue与Topic比较如下图所示:

使用maven管理依赖包,增加pom.xml文件如下:
<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>
队列(Queue)消息的收发
点对点消息,如果没有消费者在监听队列,消息将保留在队列中,直至消息消费者连接到队列为止。这种消息传递模型是传统意义上的懒模型或轮询模型。在此模型中,消息不是自动推动给消息消费者的,而是要由消息消费者从队列中请求获得(拉模式)。
Spring配置文件内容如下:
<?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="com.yoodb.mq.queue.ProducerServiceImpl">
<property name="jmsTemplate" ref="jmsTemplate"></property>
</bean> <!--queue消息消费者 -->
<bean id="consumerService" class="com.yoodb.mq.queue.ConsumerServiceImpl">
<property name="jmsTemplate" ref="jmsTemplate"></property>
</bean>
</beans>
消息生产者使用Spring JMS消息,减少重复代码(接口类ProducerService代码省略)如下:
package com.yoodb.mq.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;
} }
消息消费者代码如下:
package com.yoodb.mq.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;
} }
队列消息监听,在接受消息的时候,可以不用消息消费者代码的方式,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="com.yoodb.mq.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 com.yoodb.mq.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();
}
} }
主题(Topic)消息收发
pub/sub消息传递模型基本上是一个推模型。在该模型中,消息会自动广播,消息消费者无须通过主动请求或轮询主题的方法来获得新的消息。在使用Spring JMS的时候,主题[订阅/发布](Topic)和队列消息模式的主要差异体现在JmsTemplate中"pubSubDomain"是否设置为True。如果为True,则是Topic;如果是false或者默认,则是Queue。
<property name="pubSubDomain" value="true" />
Spring配置文件内容如下:
<!-- 定义消息主题(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="com.yoodb.mq.topic.TopicProvider">
<property name="topicJmsTemplate" ref="topicJmsTemplate"></property>
</bean> <!-- 消息主题监听者 和 主题监听容器 可以配置多个,即多个订阅者 -->
<!-- 消息主题监听者(Topic) -->
<bean id="topicMessageListener" class="com.yoodb.mq.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>
消息发布者代码如下:
package com.yoodb.mq.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;
}
}
消息订阅者(监听)代码如下:
package com.yoodb.mq.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();
}
}
}
测试代码如下:
package com.yoodb.mq;
import javax.jms.Destination;
import com.yoodb.mq.queue.ConsumerService;
import com.yoodb.mq.queue.ProducerService;
import com.yoodb.mq.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!");
}
}
测试结果如下:
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!
其他相关文章推荐:
ActiveMQ消息队列从入门到实践(4)—使用Spring JMS收发消息
ActiveMQ消息队列从入门到实践(3)—通过ActiveMQ收发消息
ActiveMQ消息队列从入门到实践(2)—Windows安装activemq服务
ActiveMQ消息队列从入门到实践(1)—JMS的概念和JMS消息模型
ActiveMQ消息队列从入门到实践(4)—使用Spring JMS收发消息的更多相关文章
- ActiveMQ消息队列从入门到实践(1)—JMS的概念和JMS消息模型
1. 面向消息的中间件 1.1 什么是MOM 面向消息的中间件,Message Oriented Middleware,简称MOM,中文简称消息中间件,利用高效可靠的消息传递机制进行平台无关的数据交流 ...
- ActiveMQ学习笔记(5)——使用Spring JMS收发消息
摘要 ActiveMQ学习笔记(四)http://my.oschina.net/xiaoxishan/blog/380446 中记录了如何使用原生的方式从ActiveMQ中收发消息.可以看出,每次 ...
- 消息队列 RabbitMQ 入门介绍
来源:http://ityen.com/archives/578 一.什么是RabbitMQ? RabbitMQ是实现AMQP(高级消息队列协议)的消息中间件的一种,最初起源于金融系统,用于在分布式系 ...
- 消息队列 MQ 入门理解
功能特性: 应用场景: 消息队列 MQ 可应用于如下几个场景: 分布式事务 在传统的事务处理中,多个系统之间的交互耦合到一个事务中,响应时间长,影响系统可用性.引入分布式事务消息,交易系统和消息队列之 ...
- RabbitMQ .NET消息队列使用入门(一)【简单示例】
首先下载安装包,我都环境是win7 64位: 去官网下载 otp_win64_19.0.exe 和rabbitmq-server-3.6.3.exe安装好 然后开始编程了: (1)创建生产者类: cl ...
- 分布式消息队列 Celery 的最佳实践
目录 目录 不使用数据库作为 Broker 不要过分关注任务结果 实现优先级任务 应用 Worker 并发池的动态扩展 应用任务预取数 保持任务的幂等性 应用任务超时限制 善用任务工作流 合理应用 a ...
- 消息队列mq总结(重点看,比较了主流消息队列框架)
转自:http://blog.csdn.net/konglongaa/article/details/52208273 http://blog.csdn.net/oMaverick1/article/ ...
- 消息队列系列(一):.Net平台下的消息队列介绍
本系列主要记录最近学习消息队列的一些心得体会,打算形成一个系列文档.开篇主要介绍一下.Net平台下一些主流的消息队列框架. RabbitMQ:http://www.rabbitmq.com ...
- 第1节 kafka消息队列:1、kafka基本介绍以及与传统消息队列的对比
1. Kafka介绍 l Apache Kafka是一个开源消息系统,由Scala写成.是由Apache软件基金会开发的一个开源消息系统项目. l Kafka最初是由LinkedIn开发,并于20 ...
随机推荐
- PythonI/O进阶学习笔记_7.python动态属性,__new__和__init__和元类编程(上)
content: 上: 1.property动态属性 2.__getattr__和__setattr__的区别和在属性查找中的作用 3.属性描述符 和属性查找过程 4.__new__和__init__ ...
- DG中模拟failover故障与恢复
问题描述:情形是当主库真正出现异常之后,才会执行的操作,那么我们执行过failover 之后,如何在重新构建DG,这里我们利用flashback database来重构.模拟前主库要开启闪回区,否则要 ...
- JS进阶面试题整理(仅仅整理我做错的题)
前几天看到掘金博客一篇文章,找到了这个JavaScript进阶问题列表:现在把地址贴出来,想找工作或者想要巩固自己JS的同学可以参考 该文档会不定时更新 一.箭头函数 箭头函数相当于匿名函数,并 ...
- 程序员的算法课(6)-最长公共子序列(LCS)
版权声明:本文为博主原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明. 本文链接:https://blog.csdn.net/m0_37609579/article/de ...
- 机器学习实战书-第二章K-近邻算法笔记
本章介绍第一个机器学习算法:A-近邻算法,它非常有效而且易于掌握.首先,我们将探讨女-近邻算法的基本理论,以及如何使用距离测量的方法分类物品:其次我们将使用?7««^从文本文件中导人并解析数据: 再次 ...
- Maven项目多环境之间的配置文件的切换
前言:对于一个项目,开发和生产环境之间会使用不同的配置文件,最简单的例子就是数据库连接池的配置了.当然,可以在打包上线前对配置文件进行替换,不过这也太low了吧. 简单的pom.xml中的配置内容 比 ...
- shell一键部署nginx+tomcat
1.首先拉取环境 tomcat需要用到jdk环境 提前准备好nginx源码包,放于指定目录下 vim test.sh #!/bin/bash yum -y install gcc gcc-c++ z ...
- Python之HTTP静态Web服务器开发
众所周知,Http协议是基于Tcp协议的基础上产生的浏览器到服务器的通信协议 ,其根本原理也是通过socket进行通信. 使用HTTP协议通信,需要注意其返回的响应报文格式不能有任何问题. 响应报文, ...
- UITableView 相关方法
最近闲来无事,总结一下 UITableViewDataSource和 UITableViewDelegate方法 UITableViewDataSource @required - (NSIntege ...
- Unity3D for iOS初级教程:Part 3/3(上)
转自:http://www.cnblogs.com/alongu3d/archive/2013/06/01/3111738.html 欢迎来到第三部分,这是Unity 3D for iOS初级系列教程 ...