一、下载安装:
操作系统:centos7
- wget http://archive.apache.org/dist/activemq/5.15.10/apache-activemq-5.15.10-bin.tar.gz
- tar -zxvf apache-activemq-5.15.10-bin.tar.gz
- ./activemq start > ../mylog.log 启动mq,并将日志记录进指定文件
- 防火墙开放 8161(默认访问端口,提供页面控制台服务)和 61616(默认进程端口,提供JMS服务)
- http://ip:8161/admin 进行访问,初始账号密码:admin/admin
二、使用
1、pom.xml文件引入activemq的jar包
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-all</artifactId>
<version>5.15.10</version>
</dependency>
<dependency>
<groupId>org.apache.xbean</groupId>
<artifactId>xbean-spring</artifactId>
<version>3.16</version>
</dependency>
三、原理
底层是JMS,java消息服务,J2EE中的一个重要规范,定义了两个应用程序之间异步通信的API接口,使我们的程序可以到达异步、解耦、削峰的效果。
- JMS简介
消息模型分为2种:
- 点对点模式Point-to-Point(P2P),队列queue
- 发布/订阅模式Publish/Subscribe(Pub/Sub),topic主题
点对点模式Point-to-Point(P2P),队列queue
一条消息仅能对应一个消费者,多个消费者一个生产者的情况,每个消费者轮询获取消息;
消息被消费后,队列中不会再有该条消息;
消费者和生产者的启动顺序可以随意;
如果没有消费者,消息也不会被丢弃;
示例
创建一个点对点的生产者
String brokerUrl = "tcp://localhost:61616";
String queueName = "第一个消息队列";
// 1、创建连接工厂
ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(brokerUrl);
// 2、创建连接
Connection connection = connectionFactory.createConnection();
connection.start();
// 3、创建会话session 第一个参数:是否开启事务;第二个参数:应答模式
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
// 4、创建目的地
Queue queue = session.createQueue(queueName);
// 5、创建消息生产者
MessageProducer producer = session.createProducer(queue);
// 6、创建3条消息
for (int i = 1; i <= 3; i++) {
TextMessage textMessage = session.createTextMessage();
textMessage.setText("第"+i+"条消息");
// 7、生产者发送消息
producer.send(textMessage);
}
// 8、关闭资源
producer.close();
session.close();
connection.close();
点对对消费者
public static void main(String[] args) throws JMSException, IOException {
String brokerUrl = "tcp://localhost:61616";
String queueName = "第一个消息队列";
// 1、创建连接工厂
ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(brokerUrl);
// 2、创建连接
Connection connection = connectionFactory.createConnection();
connection.start();
// 3、创建会话session 第一个参数:是否开启事务;第二个参数:应答模式
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
// 4、创建目的地
Queue queue = session.createQueue(queueName);
// 5、创建消息消费者
MessageConsumer consumer = session.createConsumer(queue);
// 设置异步非阻塞消息监听器获取消息
consumer.setMessageListener((message)->{
TextMessage message1 = (TextMessage) message;
try {
System.out.println("我是消费者1:"+message1.getText());
} catch (JMSException e) {
e.printStackTrace();
}
});
// 阻塞,防止未获取消息就结束了
System.in.read();
// 8、关闭资源
consumer.close();
session.close();
connection.close();
}
发布/订阅模式Publish/Subscribe(Pub/Sub),topic主题
一条消息可以对应多个消费者;
消费者只能接收订阅以后的消息,订阅前的消息获取不到,所以要先启动消费者再启动生产者;
如果没有消费者,消息会被丢弃;
示例
创建 发布/订阅 模式的生产者
public static void main(String[] args) throws Exception{
String brokerUrl = "tcp:/