ActiveMQ
ActiveMQ相比较其他中间件如kafka、RabbitMQ,对JMS服务的集成效果还不错,而且是老牌的消息中间件,故练习搭建一下
JMS
Java消息服务(Java Message Service)即JMS,是一个Java平台中关于面向消息中间件的API,用于两个程序之间,或分布式系统中发送消息,进行异步通信。
JMS与ActiveMQ
JMS包括队列与主题两种模式,一种是点对点的Queue,还有一个是发布订阅的Topic方式
- 对于Queue模式,一个发布者发布消息,下面的接收者按队列顺序接收,比如发布了10个消息,两个接收者A,B那就是A,B总共会收到10条消息,不重复。
- 对于Topic模式,一个发布者发布消息,有两个接收者A,B来订阅,那么发布了10条消息,A,B各收到10条消息
环境搭建
官网下载安装包解压即可
http://activemq.apache.org/
而后用管理员运行InstallService.bat
打开window服务
启动ActiveMQ
访问Manage broker
访问localhost:8161
默认账户密码是admin=admin
如下图
服务启动成功,
可以看到此时空的消息队列
生产者消费者代码
主题模式
package com.activemq.sample;
import org.apache.activemq.ActiveMQConnectionFactory;
import javax.jms.*;
/**
* 生产者(主题模式)
**/
public class TopicProducer {
private static final String url = "tcp://localhost:61616";
private static final String topicName = "topic-test";
public static void main(String[] args) throws JMSException {
//1.创建ConnectionFactory
ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(url);
//2.创建连接
Connection connection = connectionFactory.createConnection();
//3.启动连接
connection.start();
//4.创建会话
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
//5.创建一个目标
Destination destination = session.createTopic(topicName);
//6.创建一个生产者
MessageProducer producer = session.createProducer(destination);
for (int i = 0; i < 100; i++) {
//7.创建消息
TextMessage textMessage = session.createTextMessage("hello,ActiveMQ" + i);
producer.send(textMessage);
System.out.println("发送消息:" + textMessage.getText());
}
//8.关闭连接
connection.close();
}
}
package com.activemq.sample;
import org.apache.activemq.ActiveMQConnectionFactory;
import javax.jms.*;
/**
* 消费者(主题模式)
**/
public class TopicConsumer {
private static final String url="tcp://localhost:61616";
private static final String topicName="topic-test";
public static void main(String[] args) throws JMSException {
//1.创建ConnectionFactory
ConnectionFactory connectionFactory=new ActiveMQConnectionFactory(url);
//2.创建连接
Connection connection = connectionFactory.createConnection();
//3.启动连接
connection.start();
//4.创建会话
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
//5.创建一个目标
Destination destination = session.createTopic(topicName);
//6.创建一个消费者
MessageConsumer consumer=session.createConsumer(destination);
//7.创建一个监听器
consumer.setMessageListener(new MessageListener() {
public void onMessage(Message message) {
TextMessage textMessage= (TextMessage) message;
try {
System.out.println("接收消息:"+textMessage.getText());
} catch (JMSException e) {
e.printStackTrace();
}
}
});
}
}
pom.xml依赖
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-all</artifactId>
<version>5.15.0</version>
</dependency>
运行效果
可以在Manager中看到消费情况