1.什么是ActiveMQ
ActiveMQ就是完全基于JMS规范实现的一个消息中间件产品。是 Apache 开源基金会研发的消息中间件。ActiveMQ 主要应用在分布式系统架构中,帮助构建高可用、高性能、可伸缩的企业级面向消息服务的系统。
如需了解什么是消息中间件,请点击[传送门]:消息中间件的介绍
如需了解JMS规范,请点击[传送门]:JMS规范
2.ActiveMQ的特性
1.多语言和协议编写客户端
语言:java/C/C++/C#/Ruby/Perl/Python/PHP
应用协议:openwire/stomp/REST/ws/notification/XMPP/AMQP
2.完全支持 JMS1.1 和 J2EE1.4 规范
3.对 Spring 的支持,ActiveMQ 可以很容易内嵌到 Spring 模块中
3.ActiveMQ的安装
请移步参考:ActiveMQ-5.15.9安装(Linux)
4.ActiveMQ简单代码实现
引入Maven依赖
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-all</artifactId>
<version>5.15.9</version>
</dependency>
Producer消息生产者
public class Producer {
public static void main(String[] args) throws InterruptedException {
//1.创建连接工厂
ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://192.168.204.201:61616");
Connection connection = null;
Session session = null;
MessageProducer producer = null;
try {
//2.获取连接
connection = connectionFactory.createConnection();
//3.启动连接
connection.start();
//获取session会话 (
//参数1:是否启动事务,
//参数2:消息确认模式
//[ AUTO_ACKNOWLEDGE = 1 自动确认 | CLIENT_ACKNOWLEDGE = 2 客户端手动确认 | DUPS_OK_ACKNOWLEDGE = 3 自动批量确认 | SESSION_TRANSACTED = 0 事务提交并确认]
session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
//5.创建队列对象(目的地)
Destination destination = session.createQueue("myQueue");
//6.创建消息生产者
MessageProducer producer = session.createProducer(destination);
TextMessage message = null;
for (int i = 0; i < 100 ; i++) {
//7.创建消息
message = session.createTextMessage("ActiveMQ:"+i);
//8.发送消息
producer.send(message);
//睡眠1s钟的形式,来模拟数据的实时产生
Thread.sleep(1000);
//9.会话提交
session.commit();
}
} catch (JMSException e) {
e.printStackTrace();
} finally {
//10.关闭资源
try {
if(producer != null){
producer.close();
}
if(connection != null){
connection.close();
}
if(session != null) {
session.close();
}
} catch (JMSException e) {
e.printStackTrace();
}
}
}
}
Consumer 消费者
public class Receiver {
public static void main(String[] args) {
ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://192.168.204.201:61616");
Connection connection = null;
Session session = null;
MessageConsumer consumer = null;
try {
connection = connectionFactory.createConnection();
connection.start();
session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
Destination destination = session.createQueue("myQueue");
//创建消息消费者
consumer = session.createConsumer(destination);
Session finalSession = session;
//监听消息
consumer.setMessageListener((message)->{
TextMessage textMessage = (TextMessage) message;
try {
System.out.println(textMessage.getText());
finalSession.commit();
} catch (Exception e) {
e.printStackTrace();
}
});
System.in.read();
} catch (JMSException e) {
e.printStackTrace();
} finally {
try {
if(consumer != null){
consumer.close();
}
if(connection != null){
connection.close();
}
if(session != null) {
session.close();
}
} catch (JMSException e) {
e.printStackTrace();
}
}
}
}
END