ActiveMQ由于实例较少,编写比较麻烦,之前找到不少这方面的实现,逻辑上一直不清楚。这里看到淮少吧的系列文章,有了较深入了解。借鉴淮少吧的程序,改写个比较容易理解的程序。
用ActiveMQ收发消息,首先需要安装、启动服务器,再编写发、收程序,最后运行发收程序测试。
1. 安装、启动服务器
参见 服务器部署和维护说明
2. 编写发收程序
a) 引入jar包
b) 发送端程序
发送端的send函数,参数queue为对列名,text为要传递的文本消息。
public staticvoid send(String queue,String text){
try {
// 创建一个连接工厂
String url ="tcp://localhost:61616";
ActiveMQConnectionFactoryconnectionFactory = new ActiveMQConnectionFactory(url);
// 设置用户名和密码,这个用户名和密码在conf目录下的credentials.properties文件中,也可以在activemq.xml中配置
connectionFactory.setUserName("system");
connectionFactory.setPassword("manager");
// 创建连接
Connection connection =connectionFactory.createConnection();
connection.start();
// 创建Session,参数解释:
// 第一个参数是否使用事务:当消息发送者向消息提供者(即消息代理)发送消息时,消息发送者等待消息代理的确认,没有回应则抛出异常,消息发送程序负责处理这个错误。
// 第二个参数消息的确认模式:
// AUTO_ACKNOWLEDGE :指定消息提供者在每次收到消息时自动发送确认。消息只向目标发送一次,但传输过程中可能因为错误而丢失消息。
// CLIENT_ACKNOWLEDGE :由消息接收者确认收到消息,通过调用消息的acknowledge()方法(会通知消息提供者收到了消息)
// DUPS_OK_ACKNOWLEDGE :指定消息提供者在消息接收者没有确认发送时重新发送消息(这种确认模式不在乎接收者收到重复的消息)。
Session session =connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
// 创建目标,就创建主题也可以创建队列
Destination destination =session.createQueue(queue);
// 创建消息生产者
MessageProducer producer =session.createProducer(destination);
// 设置持久化,DeliveryMode.PERSISTENT和DeliveryMode.NON_PERSISTENT
producer.setDeliveryMode(DeliveryMode.PERSISTENT);
// 创建消息
// String text = "Hello ActiveMQ!";
TextMessage message =session.createTextMessage(text);
// 发送消息到ActiveMQ
producer.send(message);
System.out.println("Message issent!");
// 关闭资源
session.close();
connection.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
c) 接收端程序
public static void get(String queue){
try{
String url = "tcp://localhost:61616";
ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(url);
// 设置用户名和密码,这个用户名和密码在conf目录下的credentials.properties文件中,也可以在activemq.xml中配置
connectionFactory.setUserName("system");
connectionFactory.setPassword("manager");
// 创建连接
Connection connection= connectionFactory.createConnection();
connection.start();
// 创建Session
Session session= connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
// 创建目标,就创建主题也可以创建队列
Destinationdestination = session.createQueue(queue);
// 创建消息消费者
MessageConsumerconsumer = session.createConsumer(destination);
// 接收消息,参数:接收消息的超时时间,为0的话则不超时,receive返回下一个消息,但是超时了或者消费者被关闭,返回null
Message message =consumer.receive(1000);
if (message instanceofTextMessage) {
TextMessagetextMessage = (TextMessage) message;
String text =textMessage.getText();
System.out.println("Received: " + text);
} else {
System.out.println("Received: " + message);
}
consumer.close();
session.close();
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
3. 运行发收程序测试
首先运行发送程序
send("name","gongqingkui");
发送完成后,可在web管理界面消息队列看到新建的name队列中的消息。可以点击查看消息的详细情况。
运行接受程序
get("name");
可见接受结果:Received: gongqingkui
再次查看消息队列,可见消息已经被接受了。
至于ActiveMQ的各种配置、架构和协议,目前还在看。