ActiveMQ学习笔记(五)——使用Spring JMS收发消息

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/1sjymHlF

时间: 2024-07-30 03:25:34

ActiveMQ学习笔记(五)——使用Spring JMS收发消息的相关文章

RabbitMQ学习笔记五:RabbitMQ之优先级消息队列

RabbitMQ优先级队列注意点: 1.只有当消费者不足,不能及时进行消费的情况下,优先级队列才会生效 2.RabbitMQ3.5以后才支持优先级队列 代码在博客:RabbitMQ学习笔记三:Java实现RabbitMQ之与Spring集成 最后面有下载地址,只是做了少许改变,改变的代码如下: 消费者 spring-config.xml(还需要增加一个QueueListener监听器,代码就不复制到这里了,可以参考项目中的其他监听器) <!-- =========================

ActiveMQ学习笔记(六)——JMS消息类型

1.前言 ActiveMQ学习笔记(四)--通过ActiveMQ收发消息http://my.oschina.net/xiaoxishan/blog/380446 和ActiveMQ学习笔记(五)--使用Spring JMS收发消息http://my.oschina.net/xiaoxishan/blog/381209   中,发送和接受的消息类型都是TextMessage,即文本消息(如下面的代码所示).显然消息类型只有文本类型是不能满足要求的. //发送文本消息  session.create

Caliburn.Micro学习笔记(五)----协同IResult

Caliburn.Micro学习笔记(五)----协同IResult 今天说一下协同IResult 看一下IResult接口 /// <summary> /// Allows custom code to execute after the return of a action. /// </summary> public interface IResult { /// <summary> /// Executes the result using the specif

angular学习笔记(五)-阶乘计算实例(1)

<!DOCTYPE html> <html ng-app> <head> <title>2.3.2计算阶乘实例1</title> <meta charset="utf-8"> <script src="../angular.js"></script> <script src="script.js"></script> </

NLTK学习笔记(五):分类和标注词汇

[TOC] 词性标注器 之后的很多工作都需要标注完的词汇.nltk自带英文标注器pos_tag import nltk text = nltk.word_tokenize("And now for something compleyely difference") print(text) print(nltk.pos_tag(text)) 标注语料库 表示已经标注的标识符:nltk.tag.str2tuple('word/类型') text = "The/AT grand/J

Linux System Programming 学习笔记(五) 进程管理

1. 进程是unix系统中两个最重要的基础抽象之一(另一个是文件) A process is a running program A thread is the unit of activity inside of a process the virtualization of memory is associated with the process, the threads all share the same memory address space 2. pid The idle pro

《Spring学习笔记》:Spring、Hibernate、struts2的整合(以例子来慢慢讲解,篇幅较长)

<Spring学习笔记>:Spring.Hibernate.struts2的整合(以例子来慢慢讲解,篇幅较长) 最近在看马士兵老师的关于Spring方面的视频,讲解的挺好的,到了Spring.Hibernate.struts2整合这里,由于是以例子的形式来对Spring+Hibernate+struts2这3大框架进行整合,因此,自己还跟着写代码的过程中,发现还是遇到了很多问题,因此,就记录下. 特此说明:本篇博文完全参考于马士兵老师的<Spring视频教程>. 本篇博文均以如下这

java之jvm学习笔记五(实践写自己的类装载器)

java之jvm学习笔记五(实践写自己的类装载器) 课程源码:http://download.csdn.net/detail/yfqnihao/4866501 前面第三和第四节我们一直在强调一句话,类装载器和安全管理器是可以被动态扩展的,或者说,他们是可以由用户自己定制的,今天我们就是动手试试,怎么做这部分的实践,当然,在阅读本篇之前,至少要阅读过笔记三. 下面我们先来动态扩展一个类装载器,当然这只是一个比较小的demo,旨在让大家有个比较形象的概念. 第一步,首先定义自己的类装载器,从Clas

WEB前端学习笔记 五

接web前端学习笔记第四篇,此篇为web学习笔记 五,在此感谢您的采集和转发,但请注明文章出自网知博学. 2.0.3  html标签的属性格式 现在我们知道了两个双标签分别是,标题标签:<h1> - <h6>.和段落标签:<p></p>还知道了一个换行的单标签:<br />,现在我们给<p></p>标签添加一个属性,来改变段落是右对齐,还是左对齐,还是居中. 如上图,<p>标签中的 align(中文就是排列的意