您的位置:首页 > 编程语言 > Java开发

ActiveMQ安装与Spring整合

2017-05-08 11:51 344 查看

一ActiveMQ安装

1.下载ActiveMQ

进入http://activemq.apache.org/下载ActiveMQ



2.什么是ActiveMQ

ActiveMQ 是Apache出品,最流行的,能力强劲的开源消息总线。ActiveMQ 是一个完全支持JMS1.1和J2EE 1.4规范的 JMS Provider实现,尽管JMS规范出台已经是很久的事情了,但是JMS在当今的J2EE应用中间仍然扮演着特殊的地位。

主要特点:

1. 多种语言和协议编写客户端。语言: Java, C, C++, C#, Ruby, Perl, Python, PHP。应用协议: OpenWire,Stomp REST,WS Notification,XMPP,AMQP

2. 完全支持JMS1.1和J2EE 1.4规范 (持久化,XA消息,事务)

3. 对Spring的支持,ActiveMQ可以很容易内嵌到使用Spring的系统里面去,而且也支持Spring2.0的特性

4. 通过了常见J2EE服务器(如 Geronimo,JBoss 4, GlassFish,WebLogic)的测试,其中通过JCA 1.5 resource adaptors的配置,可以让ActiveMQ可以自动的部署到任何兼容J2EE 1.4 商业服务器上

5. 支持多种传送协议:in-VM,TCP,SSL,NIO,UDP,JGroups,JXTA

6. 支持通过JDBC和journal提供高速的消息持久化

7. 从设计上保证了高性能的集群,客户端-服务器,点对点

8. 支持Ajax

9. 支持与Axis的整合

10. 可以很容易得调用内嵌JMS provider,进行测试

3. ActiveMQ的消息形式

对于消息的传递有两种类型:

一种是点对点的,即一个生产者和一个消费者一一对应;

另一种是发布/订阅模式,即一个生产者产生消息并进行发送后,可以由多个消费者进行接收,也可以称之为广播模式。

JMS定义了五种不同的消息正文格式,以及调用的消息类型,允许你发送并接收以一些不同形式的数据,提供现有消息格式的一些级别的兼容性。

  · StreamMessage – Java原始值的数据流

  · MapMessage–一套名称-值对

  · TextMessage–一个字符串对象

  · ObjectMessage–一个序列化的 Java对象

  · BytesMessage–一个字节的数据流

二 ActiveMQ安装

1.解压安装

将下载好的apache-activemq-5.11.1-bin.tar.gz解压缩,安装到指定目录  

解压命令: tar -zxvf apache-activemq-5.11.1-bin.tar.gz -C /usr/local



安装好后,cd 到 安装目录 /usr/local 下 的activeMQ中



这里可以看到一个activemq-all-5.11.1jar包,编写代码的时候可以引用它,但是要使用Spring 进行整合的话,就最好不用这个jar包,因为这个jar包里包含了Spring,容易造成版本冲突。

2.启动

cd 到 /usr/local/apache-activemq-5.11.1/bin 目录下,执行./activemq start命令:



看到下面的日志信息,即启动成功。还可以通过浏览器访问监控台的方式:

在浏览器中输入:ip:8161(默认监控台的端口号)/admin ,提示输入用户名和密码,默认都是admin ,验证通过后会响应下面的页面:



注意:有可能访问监控台的其他页面会报503错误,可以尝试查看一下机器名是否配置。

查看机器名命令:cat /etc/sysconfig/network

修改host文件命令 :vim /etc/hosts

在 127.0.0.1 对应的节点最后加上本机的机器名再重启ActiveMQ服务即可。

三 使用ActiveMQ

1.point to point 形式

(1)使用maven加载activeMQ jar包

<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-all</artifactId>
<version>5.11.2</version>
</dependency>


(2)Producer 生产者端

public class TestActiveMQ {

@Test
public void testProducer()throws Exception{

//  第一步:创建ConnectionFactory对象,需要指定服务端ip及端口号。
ConnectionFactory connectionFactory = new   ActiveMQConnectionFactory("tcp://192.168.220.136:61616");
//  第二步:使用ConnectionFactory对象创建一个Connection对象。
Connection connection = connectionFactory.createConnection();
//  第三步:开启连接,调用Connection对象的start方法。
connection.start();
//  第四步:使用Connection对象创建一个Session对象。
//参数:transacted :是否开启分布式事务(一般不使用,保证数据的最终一致即可,可以使用消息队列实现)
//    acknowledgeMode:消息的应答模式,分为手动应答和自动应答,一般使用自动应答(如果第一个参数为true,这个参数无意义)
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
//  第五步:使用Session对象创建一个Destination对象(topic、queue),此处创建一个Queue对象。
//Queue是一个接口,它继承Destination(也是一个接口)
Queue queue = session.createQueue("test-queue");//指定消息队列的名称
//  第六步:使用Session对象创建一个Producer对象。
MessageProducer producer = session.createProducer(queue);//生产者向指定的queue发送消息
//  第七步:创建一个Message对象,创建一个TextMessage对象。
/*TextMessage message = new ActiveMQTextMessage();
message.setText("Hello ActiveMQ !");*/
//也可以使用session创建message
TextMessage message = session.createTextMessage("Hello ActiveMQ !");
//  第八步:使用Producer对象发送消息。
producer.send(message);
//  第九步:关闭资源。
producer.close();
session.close();
connection.close();
}
}


运行单元测试,访问监控台,点击Queues,可以看到消息已经成功发送到MQ上:



再点击test-queue,可以看到更详细的信息。

(3)Consumer 消费者

@Test
public void testQueueConsumer() throws Exception {
// 第一步:创建一个ConnectionFactory对象。
ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://192.168.220.136:61616");
// 第二步:从ConnectionFactory对象中获得一个Connection对象。
Connection connection = connectionFactory.createConnection();
// 第三步:开启连接。调用Connection对象的start方法。
connection.start();
// 第四步:使用Connection对象创建一个Session对象。
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
// 第五步:使用Session对象创建一个Destination对象。和发送端保持一致queue,并且队列的名称一致。
Queue queue = session.createQueue("test-queue");
// 第六步:使用Session对象创建一个Consumer对象。
MessageConsumer consumer = session.createConsumer(queue);
// 第七步:接收消息。
consumer.setMessageListener(new MessageListener() {

@Override
public void onMessage(Message message) {
try {
TextMessage textMessage = (TextMessage) message;
String text = null;
//取消息的内容
text = textMessage.getText();
// 第八步:打印消息。
System.out.println(text);
} catch (JMSException e) {
e.printStackTrace();
}
}
});
//等待键盘输入
System.in.read();
// 第九步:关闭资源
consumer.close();
session.close();
connection.close();
}


运行程序,在console 可以看到获取到的消息:



在就监控台上也可以看到消费信息:



Number Of Consumers :当前消费者的数量

Messages Enqueued :入队的消息数量 (生产的消息数量)

Messages Dequeued :出队的消息数量(被消费的消息数量)

2.publish/subscribe 形式 (发布订阅形式)

发布订阅形式与点对点形式代码上大同小异,只有在第五步的时候,创建的不是Queue对象,而是Topic 对象。这里就不再详述。但值得注意的是,使用Topic 发送消息到MQ上时,消息默认是不持久化到服务端的。生产服务关闭后,消息就会丢失。所以消费的时候要保证生产端是启动的状态。或者先启动消费端等待,再启动生产端。

3.Spring整合ActiveMQ

(1)通常我们都是通过Spring整合ActiveMQ的方式来只用MQ,这里需要加入两个jar包

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jms</artifactId>
<version>4.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>4.2.4.RELEASE</version>
</dependency>


(2)创建spring配置文件:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
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-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.2.xsd"> 
<!-- JMS服务厂商提供的ConnectionFactory -->
<bean id="targetConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
<constructor-arg name="brokerURL" value="tcp://192.168.220.136:61616"/>
</bean>
<!-- spring对ConnectionFactory的封装 -->
<bean id="connectionFactory" class="org.springframework.jms.connection.SingleConnectionFactory">
<property name="targetConnectionFactory" ref="targetConnectionFactory"/>
</bean>

<!-- 配置JMSTemplate -->
<bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
<property name="connectionFactory" ref="connectionFactory"/>
</bean>
<!-- 配置Destination对象 -->
<bean id="queue" class="org.apache.activemq.command.ActiveMQQueue">
<constructor-arg name="name" value="test-queue"/>
</bean>
<bean id="topic" class="org.apache.activemq.command.ActiveMQTopic">
<constructor-arg name="name" value="test-topic"/>
</bean>
</beans>


(3)使用JmsTemplate发送消息

@Test
public void testSpringActiveMQ()throws Exception{
//第一步:初始化spring容器
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:spring/applicationContext-actvicemq.xml");
//第二步:从容器中获取JmsTemplate对象
JmsTemplate jmsTemplate = applicationContext.getBean(JmsTemplate.class);
//第三步:从容器中获取Destination对象
Destination destination = (Destination)applicationContext.getBean("queue");
//第四步:发送消息
jmsTemplate.send(destination, new MessageCreator() {

@Override
public Message createMessage(Session session) throws JMSException {

TextMessage message = session.createTextMessage("Spring 整合 ActiveMQ 测试信息");

return message;
}
});
}


运行测试代码,这里就使用point to point 形式中的消费方法进行测试:



(4)接受消息

首先创建一个MessageListenerl实现类

public class MyMessageListener implements MessageListener {

@Override
public void onMessage(Message message) {
try {
TextMessage textMessage = (TextMessage) message;
//取消息内容
String text = textMessage.getText();
System.out.println(text);
} catch (JMSException e) {
e.printStackTrace();
}
}
}


配置文件与之前的大致相同,只需删除到JmsTemplate的配置,并且加入接收消息的配置即可:

<!-- 接收消息 -->
<!-- 配置监听器 -->
<bean id="myMessageListener" class="com.jakerfei.listener.MyMessageListener" />
<!-- 消息监听容器 -->
<bean class="org.springframework.jms.listener.DefaultMessageListenerContainer">
<property name="connectionFactory" ref="connectionFactory" />
<property name="destination" ref="queue" />
<property name="messageListener" ref="myMessageListener" />
</bean>


消费者测试代码:这里这要启动spring容器就可以接收到消息

@Test
public void testQueueConsumer() throws Exception {
//初始化spring容器
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:spring/applicationContext-actvicemq.xml");
//等待
System.in.read();
}


测试结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  spring activemq 应用