一.安装ActiveMQ
1. 下载压缩包:http://download.csdn.net/detail/mgl_1/9901322
2. 直接解压,运行bin目录下对应的win32或者win64下的activemq.bat
3. 运行成功后,输入http://localhost:8161地址,并输入admin和admin可访问web页面
二.简单的HelloWorld实例(首先启动ActiveMQ服务:activemq.bat)
因为ActiveMQ是基于JMS规范实现的生产者和消费者之间通信的库,所以代码需要分为两部分。
1. 以下是生产者的代码:
public class ActiveMQProducer
{
public static void main(String[] args) throws Exception
{
// 连接工厂,实例化连接工厂
ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://127.0.0.1:61616");
// 连接 通过连接工厂来获取
Connection connection = connectionFactory.createConnection();
connection.start(); // 启动连接
// 会话,接受或者发送消息的线程
// 第一个参数代表是否加事务
// 第二个参数代表是 确认消息的
Session session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
// 消息的目的地(创建消息队列)
Destination destination = session.createQueue("Test.foo");
// 消息的生产者(通过session来创建消息生产者)
MessageProducer producer = session.createProducer(destination);
// 设置是否持久化
producer.setDeliveryMode(DeliveryMode.PERSISTENT);
for (int i = 0; i < 100; i++)
{
// 通过session来创建消息
ObjectMessage message = session.createObjectMessage();
// 设置消息内容
message.setObject("hello world" + i);
System.out.println("发送的消息:" + message.getObject());
// 发送消息
producer.send(message);
}
// 因为加了事务,所以需要提交
session.commit();
// 关闭资源
session.close();
connection.close();
}
}
2.以下是消费者的代码:
public class ActiveMQCustomer
{
public static void main(String[] args) throws Exception
{
// 实例化连接工厂
ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://127.0.0.1:61616");
// 通过工厂对象获取连接
Connection connection = connectionFactory.createConnection();
connection.start();
// 获取session
final Session session = connection.createSession(Boolean.FALSE, Session.AUTO_ACKNOWLEDGE);
Destination destination = session.createQueue("Test.foo");
// 消息的消费者
MessageConsumer consumer = session.createConsumer(destination);
// 消息监听
consumer.setMessageListener(new MessageListener() {
@Override
public void onMessage(Message msg)
{
ObjectMessage message = (ObjectMessage) msg;
try
{
System.out.println("收到的消息:" + message.getObject());
} catch (JMSException e)
{
e.printStackTrace();
}
try
{
session.commit();
} catch (JMSException e)
{
e.printStackTrace();
}
}
});
TimeUnit.MINUTES.sleep(2000L);
session.close();
connection.close();
}
}
3.运行结果:
ActiveMQProducer:
发送的消息:hello world0
发送的消息:hello world1
发送的消息:hello world2
发送的消息:hello world3
发送的消息:hello world4
发送的消息:hello world5
发送的消息:hello world6
发送的消息:hello world7
发送的消息:hello world8
发送的消息:hello world9
发送的消息:hello world10
ActiveMQCustomer:
收到的消息:hello world0
收到的消息:hello world1
收到的消息:hello world2
收到的消息:hello world3
收到的消息:hello world4
收到的消息:hello world5
收到的消息:hello world6
收到的消息:hello world7
收到的消息:hello world8
收到的消息:hello world9
收到的消息:hello world10