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.注意事项
- 最后接收者跟发送者在不同的机器上测试
- 项目所引用的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特性列表
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
- <?xml version="1.0" encoding="UTF-8"?>
- <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
- <beans>
- <bean id="connectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
- <property name="brokerURL">
- <value>tcp://localhost:61616?wireFormat.maxInactivityDuration=0</value>
- </property>
- </bean>
- <bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
- <property name="connectionFactory">
- <ref bean="connectionFactory"/>
- </property>
- </bean>
- <bean id="destination" class="org.apache.activemq.command.ActiveMQQueue">
- <constructor-arg index="0">
- <value>MessageQueue</value>
- </constructor-arg>
- </bean>
- </beans>
这时主要是配置activemq服务信息与实现springjms的对应接口
6:消息产生者
- package test;
- import javax.jms.JMSException;
- import javax.jms.Message;
- import javax.jms.Session;
- import org.springframework.jms.core.MessageCreator;
- /**
- * 消息产生者
- * User: liuwentao
- * Time: 12-6-14 上午11:31
- */
- public class MyMessageCreator implements MessageCreator {
- public int n = 0;
- private static String str1 = "这个是第 ";
- private static String str2 = " 个测试消息!";
- private String str = "";
- @Override
- public Message createMessage(Session paramSession) throws JMSException {
- System.out.println("MyMessageCreator n=" + n);
- if (n == 9) {
- //在这个例子中表示第9次调用时,发送结束消息
- return paramSession.createTextMessage("end");
- }
- str = str1 + n + str2;
- return paramSession.createTextMessage(str);
- }
- }
7:发送消息方
- package test;
- import javax.jms.Destination;
- import org.springframework.context.ApplicationContext;
- import org.springframework.context.support.ClassPathXmlApplicationContext;
- import org.springframework.jms.core.JmsTemplate;
- /**
- * 发送消息方
- * User: liuwentao
- * Time: 12-6-14 上午11:29
- */
- public class MessageSender extends Thread {
- public static void main(String args[]) throws Exception {
- String[] configLocations = new String[] {"test/applicationContext.xml"};
- ApplicationContext context = new ClassPathXmlApplicationContext(configLocations);
- JmsTemplate jmsTemplate = (JmsTemplate) context.getBean("jmsTemplate");
- Destination destination = (Destination) context.getBean("destination");
- for (int i = 1; i < 100; i++) {
- System.out.println("发送 i=" + i);
- //消息产生者
- MyMessageCreator myMessageCreator = new MyMessageCreator();
- myMessageCreator.n = i;
- jmsTemplate.send(destination, myMessageCreator);
- sleep(10000);//10秒后发送下一条消息
- }
- }
- }
8:消息接收方
- package test;
- import javax.jms.Destination;
- import javax.jms.TextMessage;
- import org.springframework.context.ApplicationContext;
- import org.springframework.context.support.ClassPathXmlApplicationContext;
- import org.springframework.jms.core.JmsTemplate;
- /**
- * 消息接收方
- * User: liuwentao
- * Time: 12-6-14 上午11:32
- */
- public class MessageReciver{
- public static void main(String args[]) throws Exception {
- String[] configLocations = new String[] {"test/applicationContext.xml"};
- ApplicationContext context = new ClassPathXmlApplicationContext(configLocations);
- JmsTemplate jmsTemplate = (JmsTemplate) context.getBean("jmsTemplate");
- Destination destination = (Destination) context.getBean("destination");
- TextMessage msg = null;
- //是否继续接收消息
- boolean isContinue = true;
- while (isContinue) {
- msg = (TextMessage) jmsTemplate.receive(destination);
- System.out.println("收到消息 :" + msg.getText());
- if (msg.getText().equals("end")) {
- isContinue = false;
- System.out.println("收到退出消息,程序要退出!");
- }
- }
- System.out.println("程序退出了!");
- }
- }
9:测试
运行 发送方和接收方 (顺序随便) main文件,效果如下:
注:即使 接收方启动晚,或者 发送方关闭了, 接收方都会正常接收完所有数据