本文将由三方面阐述JMS的应用:
- JMS
- Sprint整合ActiveMQ
- SpringBoot整合ActiveMQ
JMS
一、依赖
PTP(queue)模式生产者
<!-- https://mvnrepository.com/artifact/org.apache.activemq/activemq-core -->
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-all</artifactId>
<version>5.11.2</version>
</dependency>
二、Queue
1. 生产消息Producer
//点对点(Queue)- 消息生产者demo
public static void main(String[] args) throws JMSException {
//1、创建连接工厂
ConnectionFactory factory = new ActiveMQConnectionFactory("tcp://127.0.0.1:61616");
//2、创建连接
Connection connection = factory.createConnection();
//3、打开连接
connection.start();
//4、创建session
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
//5、创建目标地址(Queue/Topic)
Destination destination = session.createQueue("testQueue1");
//6、创建消息生产者
MessageProducer producer = session.createProducer(destination);
//7、创建消息
TextMessage textMessage = session.createTextMessage("test queue1 message");
//8、发送消息
producer.send(textMessage);
System.out.println("message send success to testQueue1");
//9、释放资源
session.close();
connection.close();
}
2. 消费消息Consumer
注意:在监听器模式下不能关闭连接,一旦关闭,消息无法接收
方式一:
public static void main(String[] args) throws JMSException {
//1、创建连接工厂
ConnectionFactory factory = new ActiveMQConnectionFactory("tcp://127.0.0.1:61616");
//2、创建连接
Connection connection = factory.createConnection();
//3、打开连接
connection.start();
//4、创建session
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
//5、指定目标地址
Destination destination = session.createQueue("testQueue1");
//6、创建消息的消费者
MessageConsumer consumer = session.createConsumer(destination);
//7、设置消息监听器来接收消息
consumer.setMessageListener(new MessageListener() {
public void onMessage(Message message) {
if (message instanceof TextMessage){
TextMessage message1 = (TextMessage)message;
try {
System.out.println(message1.getText());
} catch (JMSException e) {
e.printStackTrace();
}
}
}
});
//注意:在监听器模式下不能关闭连接,一旦关闭,消息无法接收
}
方式二:
public static void main(String[] args) throws JMSException {
//1、创建连接工厂
ConnectionFactory factory = new ActiveMQConnectionFactory("tcp://127.0.0.1:61616");
//2、创建连接
Connection connection = factory.createConnection();
//3、打开连接
connection.start();
//4、创建session
Session session &