ActiveMQ JAVA实现最重要的组成部分
> ConnectionFactory 连接工厂
> Connection 客户端连接
> Session 一个发送或接收消息的线程
> Destination 发送消息的目的地 可以 ONE-TO-ONE (点对点队列模式) 也可以 ONE-TO-MANY (一对多 订阅模式)
> MessageProducer 消息生产者
> MessageConsumer 消息消费者
ActiveMQ JAVA实现的一个简单实例
//连接工厂
ConnectionFactory connectionFactory;
//客户端连接
Connection connection = null;
//发送或接收消息的线程
Session session;
//消息的目的地
Destination destination;
//消息生产者
MessageProducer producer;
connectionFactory = new ActiveMQConnectionFactory(
"tcp://localhost:61616");
try {
// 从连接工厂获取连接
connection = connectionFactory.createConnection();
//启动连接
connection.start();
//获取一个操作线程
session = connection.createSession(Boolean.TRUE,
Session.AUTO_ACKNOWLEDGE);
//获取一个消息队列 没有就创建 也可以获取一个 Topic 订阅
destination = session.createQueue("sessionAware");
//获取消息生产者
producer = session.createProducer(destination);
//设置不持久化 或 DeliveryMode.PERSISTENT 持久化
producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
//创建一个消息
TextMessage message = session
.createTextMessage("producer send hello ActiveMQ");
// 发送消息
producer.send(message);
session.commit();
} catch (JMSException e) {
e.printStackTrace();
} finally {
try {
if (null != connection)
connection.close();
} catch (JMSException e) {
e.printStackTrace();
}
}
}
//接收消息
public static void main(String[] args) {
//连接工厂
ConnectionFactory connectionFactory;
//客户端连接
Connection connection = null;
//发送或接收消息的线程
Session session;
//消息的目的地
Destination destination;
//消息消费者
MessageConsumer consumer;
connectionFactory = new ActiveMQConnectionFactory(
"tcp://localhost:61616");
try {
connectionFactory = new ActiveMQConnectionFactory(
"tcp://localhost:61616");
// 从连接工厂获取连接
connection = connectionFactory.createConnection();
//启动连接
connection.start();
//获取一个操作线程
session = connection.createSession(Boolean.TRUE,
Session.AUTO_ACKNOWLEDGE);
//获取一个消息队列 没有就创建 也可以获取一个 Topic 订阅
destination = session.createQueue("sessionAware");
//获取消息消费者
consumer = session.createConsumer(destination);
while (true) {
//接收消息 时间为 10s
TextMessage message = (TextMessage) consumer.receive(1000*10);
if (message != null) {
System.out.println("收到生产者消息:" + message.getText());
} else
break;
}
} catch (JMSException e) {
e.printStackTrace();
} finally {
try {
if (null != connection)
connection.close();
} catch (JMSException e) {
e.printStackTrace();
}
}
}