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 ...
随机推荐
- kali linux 修改更新源和更新命令
1.修改sources.list源文件: vim /etc/apt/sources.list #aliyun 阿里云 deb http://mirrors.aliyun.com/kali kali-r ...
- Session.run() & Tensor.eval()
如果有一个Tensor t,在使用t.eval()时,等价于: tf.get_defaut_session().run(t) t = tf.constant(42.0) sess = tf.Sessi ...
- 【设计模式大法】Iterator模式
Iterator模式 --一个一个遍历 在Java中的for语句中 i++的作用是让 i 的值在每次循环后自增1,这样就可以访问数组中的下一个元素.下下一个元素.再下下一个元素,也就实现了从头至尾逐一 ...
- 三分钟带你入门 redis 高可用架构之哨兵
什么是哨兵? 哨兵(Sentinel)是 redis 的高可用性解决方案,前面我们讲的主从复制它是高可用的基础,需要人工介入才能完成故障转移,哨兵可以解决这个问题,在主从复制情况下,当主节点发生故障时 ...
- 抖音抖一抖-SVG和CSS视觉故障艺术小赏
故障艺术,英文名称叫glitch,在很多赛博朋克作品中经常看到,其实就是故意表现一种显示设备的小故障效果,抖音的图标其实就是这种的效果,我们看下这个图标 这个图标中的红色和蓝色的偏移其实就是一种故障艺 ...
- MySQL双日志
InnoDB引擎的redo log日志 解决什么问题? 我们每次更新数据如果都要直接写到硬盘存储的话,如果更新数据频繁的话,整个过程的Io成本和查找成本都会很高(比方说每次启动磁盘,平均的寻找数据时间 ...
- 《手把手教你》系列练习篇之8-python+ selenium自动化测试 -压台篇(详细教程)
1. 简介 本文是练习篇的最后一篇文章,虽然练习篇的文章到此就要和大家说拜拜了,但是我们的学习之路才刚刚开始.不要停下你的脚步,大步朝前走吧!比你优秀的人还在走着,我们有什么理由停下自己的脚步了,生命 ...
- 15 个优秀开源的 Spring Boot 学习项目,一网打尽!
Spring Boot 算是目前 Java 领域最火的技术栈了,松哥年初出版的 <Spring Boot + Vue 全栈开发实战>迄今为止已经加印了 8 次,Spring Boot 的受 ...
- Zookeeper选取机制
1)半数机制:集群中半数以上机器存活,集群可用.所以Zookeeper适合安装奇数台服务器. 2)Zookeeper虽然在配置文件中并没有指定Master和Slave.但是,Zookeeper工作时, ...
- [TimLinux] python-ldap 介绍
1. 接口 ldap: LDAP库接口 ldap.asyncsearch: 大量搜索结果数据采用流处理 ldap.controls: LDAPv3上层访问扩展控制 ldap.dn: LDAP dist ...