现在的位置: 首页 > 综合 > 正文

ActiveMQ入门实例

2018年05月24日 ⁄ 综合 ⁄ 共 9109字 ⁄ 字号 评论关闭

ActiveMQ入门实例

1.下载ActiveMQ

去官方网站下载:http://activemq.apache.org/

2.运行ActiveMQ

解压缩apache-activemq-5.5.1-bin.zip,然后双击apache-activemq-5.5.1\bin\activemq.bat运行ActiveMQ程序。

启动ActiveMQ以后,登陆:http://localhost:8161/admin/,创建一个Queue,命名为FirstQueue。

3.创建Eclipse项目并运行

创建project:ActiveMQ-5.5,并导入apache-activemq-5.5.1\lib目录下需要用到的jar文件,项目结构如下图所示:

3.1.Sender.java

复制代码
package com.xuwei.activemq;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

public class Sender {
private static final int SEND_NUMBER = 5;

public static void main(String[] args) {
// ConnectionFactory :连接工厂,JMS 用它创建连接
ConnectionFactory connectionFactory;
// Connection :JMS 客户端到JMS Provider 的连接
Connection connection = null;
// Session: 一个发送或接收消息的线程
Session session;
// Destination :消息的目的地;消息发送给谁.
Destination destination;
// MessageProducer:消息发送者
MessageProducer producer;
// TextMessage message;
// 构造ConnectionFactory实例对象,此处采用ActiveMq的实现jar
connectionFactory = new ActiveMQConnectionFactory(
ActiveMQConnection.DEFAULT_USER,
ActiveMQConnection.DEFAULT_PASSWORD,
"tcp://localhost:61616");
try {
// 构造从工厂得到连接对象
connection = connectionFactory.createConnection();
// 启动
connection.start();
// 获取操作连接
session = connection.createSession(Boolean.TRUE,
Session.AUTO_ACKNOWLEDGE);
// 获取session注意参数值xingbo.xu-queue是一个服务器的queue,须在在ActiveMq的console配置
destination = session.createQueue("FirstQueue");
// 得到消息生成者【发送者】
producer = session.createProducer(destination);
// 设置不持久化,此处学习,实际根据项目决定
producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
// 构造消息,此处写死,项目就是参数,或者方法获取
sendMessage(session, producer);
session.commit();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (null != connection)
connection.close();
} catch (Throwable ignore) {
}
}
}

public static void sendMessage(Session session, MessageProducer producer)
throws Exception {
for (int i = 1; i <= SEND_NUMBER; i++) {
TextMessage message = session
.createTextMessage("ActiveMq 发送的消息" + i);
// 发送消息到目的地方
System.out.println("发送消息:" + "ActiveMq 发送的消息" + i);
producer.send(message);
}
}
}
复制代码

3.2.Receiver.java

复制代码
package com.xuwei.activemq;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.MessageConsumer;
import javax.jms.Session;
import javax.jms.TextMessage;
import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

public class Receiver {
public static void main(String[] args) {
// ConnectionFactory :连接工厂,JMS 用它创建连接
ConnectionFactory connectionFactory;
// Connection :JMS 客户端到JMS Provider 的连接
Connection connection = null;
// Session: 一个发送或接收消息的线程
Session session;
// Destination :消息的目的地;消息发送给谁.
Destination destination;
// 消费者,消息接收者
MessageConsumer consumer;
connectionFactory = new ActiveMQConnectionFactory(
ActiveMQConnection.DEFAULT_USER,
ActiveMQConnection.DEFAULT_PASSWORD,
"tcp://localhost:61616");
try {
// 构造从工厂得到连接对象
connection = connectionFactory.createConnection();
// 启动
connection.start();
// 获取操作连接
session = connection.createSession(Boolean.FALSE,
Session.AUTO_ACKNOWLEDGE);
// 获取session注意参数值xingbo.xu-queue是一个服务器的queue,须在在ActiveMq的console配置
destination = session.createQueue("FirstQueue");
consumer = session.createConsumer(destination);
while (true) {
//设置接收者接收消息的时间,为了便于测试,这里谁定为100s
TextMessage message = (TextMessage) consumer.receive(100000);
if (null != message) {
System.out.println("收到消息" + message.getText());
} else {
break;
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (null != connection)
connection.close();
} catch (Throwable ignore) {
}
}
}
}
复制代码

4.注意事项

  1. 最后接收者跟发送者在不同的机器上测试
  2. 项目所引用的jar最后在ActiveMQ下的lib中找,这样不会出现版本冲突。

5.测试过程

因为是在单机上测试,所以需要开启两个eclipse,每一个eclipse都有自身的workspace。我们在eclipse1中运行Receiver,在eclipse2中运行Sender。

刚开始eclipse1中运行Receiver以后console介面没有任何信息,在eclipse2中运行Sender以后,eclipse2中的console显示如下信息:

发送消息:ActiveMq 发送的消息1
发送消息:ActiveMq 发送的消息2
发送消息:ActiveMq 发送的消息3
发送消息:ActiveMq 发送的消息4
发送消息:ActiveMq 发送的消息5

而回到eclipse1中发现console界面出现如下信息:

收到消息ActiveMq 发送的消息1
收到消息ActiveMq 发送的消息2
收到消息ActiveMq 发送的消息3
收到消息ActiveMq 发送的消息4
收到消息ActiveMq 发送的消息5

 PS:2012-2-27

今天发现测试并不需要开启两个eclipse,在一个eclipse下页可以启动多个程序,并且有多个console,在上面的Receiver.java中,设置一个较大的时间,比如receive(500000),如下代码所示:

TextMessage message = (TextMessage) consumer.receive(500000);

这个时候运行Receiver.java的话,会使得这个Receiver.java一直运行500秒,在eclipse中可以发现:

点击那个红色方块可以手动停止运行程序。

运行玩receiver以后我们在运行sender,在运行完sender以后,我们要切换到receiver的console,如下图所示:

ActiveMQ

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

ActiveMQ特性列表 

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,进行测试 

1:下载 ActiveMQ 5.6.0 Release 

http://activemq.apache.org/download.html 

放到d盘 

2:运行apache-activemq服务:双击 activemq.bat 

 

3:效果 

4:所需jar包 

 

5:spring配置文件applicationContext.xml 

Java代码  收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">  
  3. <beans>  
  4.     <bean id="connectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">  
  5.         <property name="brokerURL">  
  6.             <value>tcp://localhost:61616?wireFormat.maxInactivityDuration=0</value>  
  7.         </property>  
  8.     </bean>  
  9.     <bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">  
  10.         <property name="connectionFactory">  
  11.             <ref bean="connectionFactory"/>  
  12.         </property>  
  13.     </bean>  
  14.     <bean id="destination" class="org.apache.activemq.command.ActiveMQQueue">  
  15.         <constructor-arg index="0">  
  16.             <value>MessageQueue</value>  
  17.         </constructor-arg>  
  18.     </bean>  
  19. </beans>  

这时主要是配置activemq服务信息与实现springjms的对应接口 

6:消息产生者 

Java代码  收藏代码
  1. package test;  
  2. import javax.jms.JMSException;  
  3. import javax.jms.Message;  
  4. import javax.jms.Session;  
  5.   
  6. import org.springframework.jms.core.MessageCreator;  
  7.   
  8. /** 
  9.  * 消息产生者 
  10.  * User: liuwentao 
  11.  * Time: 12-6-14 上午11:31 
  12.  */  
  13. public class MyMessageCreator implements MessageCreator {  
  14.     public int n = 0;  
  15.     private static String str1 = "这个是第 ";  
  16.     private static String str2 = " 个测试消息!";  
  17.     private String str = "";  
  18.     @Override  
  19.     public Message createMessage(Session paramSession) throws JMSException {  
  20.         System.out.println("MyMessageCreator  n=" + n);  
  21.         if (n == 9) {  
  22.             //在这个例子中表示第9次调用时,发送结束消息  
  23.             return paramSession.createTextMessage("end");  
  24.         }  
  25.         str = str1 + n + str2;  
  26.         return paramSession.createTextMessage(str);  
  27.     }  
  28. }  

7:发送消息方 

Java代码  收藏代码
  1. package test;  
  2. import javax.jms.Destination;  
  3.   
  4. import org.springframework.context.ApplicationContext;  
  5. import org.springframework.context.support.ClassPathXmlApplicationContext;  
  6. import org.springframework.jms.core.JmsTemplate;  
  7. /** 
  8.  * 发送消息方 
  9.  * User: liuwentao 
  10.  * Time: 12-6-14 上午11:29 
  11.  */  
  12. public class MessageSender extends Thread {  
  13.     public static void main(String args[]) throws Exception {  
  14.         String[] configLocations = new String[] {"test/applicationContext.xml"};  
  15.         ApplicationContext context = new ClassPathXmlApplicationContext(configLocations);  
  16.         JmsTemplate jmsTemplate = (JmsTemplate) context.getBean("jmsTemplate");  
  17.         Destination destination = (Destination) context.getBean("destination");  
  18.         for (int i = 1; i < 100; i++) {  
  19.             System.out.println("发送 i=" + i);  
  20.             //消息产生者  
  21.             MyMessageCreator myMessageCreator = new MyMessageCreator();  
  22.             myMessageCreator.n = i;  
  23.             jmsTemplate.send(destination, myMessageCreator);  
  24.             sleep(10000);//10秒后发送下一条消息  
  25.         }  
  26.     }  
  27. }  

8:消息接收方 

Java代码  收藏代码
  1. package test;  
  2. import javax.jms.Destination;  
  3. import javax.jms.TextMessage;  
  4.   
  5. import org.springframework.context.ApplicationContext;  
  6. import org.springframework.context.support.ClassPathXmlApplicationContext;  
  7. import org.springframework.jms.core.JmsTemplate;  
  8. /** 
  9.  * 消息接收方 
  10.  * User: liuwentao 
  11.  * Time: 12-6-14 上午11:32 
  12.  */  
  13. public class MessageReciver{  
  14.     public static void main(String args[]) throws Exception {  
  15.         String[] configLocations = new String[] {"test/applicationContext.xml"};  
  16.         ApplicationContext context = new ClassPathXmlApplicationContext(configLocations);  
  17.   
  18.         JmsTemplate jmsTemplate = (JmsTemplate) context.getBean("jmsTemplate");  
  19.         Destination destination = (Destination) context.getBean("destination");  
  20.   
  21.         TextMessage msg = null;  
  22.         //是否继续接收消息  
  23.         boolean isContinue = true;  
  24.         while (isContinue) {  
  25.             msg = (TextMessage) jmsTemplate.receive(destination);  
  26.             System.out.println("收到消息 :" + msg.getText());  
  27.             if (msg.getText().equals("end")) {  
  28.                 isContinue = false;  
  29.                 System.out.println("收到退出消息,程序要退出!");  
  30.             }  
  31.         }  
  32.         System.out.println("程序退出了!");  
  33.     }  
  34. }  

9:测试 

运行 发送方和接收方 (顺序随便) main文件,效果如下: 

 

 

注:即使 接收方启动晚,或者 发送方关闭了, 接收方都会正常接收完所有数据 

抱歉!评论已关闭.