ActiveMQ学习
标签(空格分隔): ActiveMQ JMS
ActiveMQ简介
ActiveMQ是JMS消息通信规范的一个实现,通过ActiveMQ消息服务交换消息。消息生产者将消息发送至消息服务,消息消费者则从消息服务接收这些消息。这些消息传送操作是使用一组实现 ActiveMQ应用编程接口 (API) 的对象来执行的。
安装ActiveMQ
a.官网下载安装
http://activemq.apache.org/download-archives.html
b.brew下载安装
执行命令
brew install activemq
启动/关闭ActiveMQ
找到activemq的安装目录,执行bin/activemq start/stop
启动后:
打开http://localhost:8161/admin/,即可访问后台管理界面
生产/消费模式
生产者
package com.frankstar.producer;
import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
import javax.jms.*;
/**
* Created by frankstar on 16/7/11.
*/
public class Producer {
private static final int SENDER_NUMBER = 5;
public static void main(String[] args) {
ConnectionFactory connectionFactory;
Connection connection = null;
Session session;
Destination destination;
MessageProducer messageProducer;
connectionFactory = new ActiveMQConnectionFactory(
ActiveMQConnection.DEFAULT_BROKER_URL);
try {
connection = connectionFactory.createConnection();
connection.start();
session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
destination = session.createQueue("Frankstar");
messageProducer = session.createProducer(destination);
sendMessage(session, messageProducer);
session.commit();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (null != connection) {
connection.close();
}
} catch (Throwable ignore) {
}
}
}
private static void sendMessage(Session session, MessageProducer messageProducer) throws JMSException {
for (int i = 0; i < SENDER_NUMBER; i++) {
TextMessage textMessage = session.createTextMessage("ActiveMQ发送消息:" + i);
System.out.println("发送消息:" + "ActiveMQ 发送的消息" + i);
messageProducer.send(textMessage);
}
}
}
消费者
package com.frankstar.consumer;
import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
import javax.jms.*;
/**
* Created by frankstar on 16/7/11.
*/
public class Consumer {
public static void main(String[] args) throws JMSException {
ConnectionFactory connectionFactory;
Connection connection = null;
Session session;
Destination destination;
MessageConsumer messageConsumer;
connectionFactory = new ActiveMQConnectionFactory(
ActiveMQConnection.DEFAULT_BROKER_URL
);
try {
connection = connectionFactory.createConnection();
connection.start();
session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
destination = session.createQueue("Frankstar");
messageConsumer = session.createConsumer(destination);
while (true) {
TextMessage textMessage = (TextMessage) messageConsumer.receive(1000);
if (textMessage != null) {
System.out.println("收到消息:" + textMessage.getText());
} else {
break;
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (connection != null) {
connection.close();
}
} catch (Throwable ignore) {
}
}
}
}
测试
运行Producer的主函数,在执行Consumer的主函数,在管理界面Queue中查看信息的订阅与消费