使用@JmsListener注解方式
1. 工程目录
2. 引入依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.hik.hyy</groupId>
<artifactId>spring-boot</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>spring-boot</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.8.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-activemq</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
3.编写application.properties
#activemq
spring.activemq.broker-url=tcp://10.20.81.118:61616
spring.activemq.user=admin
spring.activemq.password=admin
spring.activemq.in-memory=true
spring.activemq.pool.enabled=false
具体含义如下:
-
#activemq
-
spring.activemq.broker-url #指定ActiveMQ broker的URL
-
spring.activemq.user #指定broker的用户.
-
spring.activemq.password #指定broker的密码.
-
spring.activemq.in-memory #是否是内存模式,默认为true.
-
spring.activemq.pooled #是否创建PooledConnectionFactory,而非ConnectionFactory,默认false
4. 编写配置类(AMQConfig)
package com.hik.hyy.jms.bootMQ;
import javax.jms.ConnectionFactory;
import org.apache.activemq.command.ActiveMQQueue;
import org.apache.activemq.command.ActiveMQTopic;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.jms.annotation.EnableJms;
import org.springframework.jms.config.DefaultJmsListenerContainerFactory;
@SpringBootConfiguration
@ComponentScan(basePackages = {"com.hik.hyy.jms.bootMQ.MessageListener"})
//使用@JmsListener注解时,需要在配置类上加上该注解以及定义一个DefaultJmsListenerContainerFactory工厂(不定义,会监听queue队列)
@EnableJms
public class AMQConfig {
//引入SpringBoot自己配置的连接工厂
@Autowired
ConnectionFactory connectionFactory;
/**
* @Description: 创建queue
*/
@Bean
public ActiveMQQueue queueDestination() {
return new ActiveMQQueue("queue1");
}
/**
* @Description: 创建topic
*/
@Bean
public ActiveMQTopic topicDestination(){
return new ActiveMQTopic("topic1");
}
/**
* @Description: 使用@JmsListener注解时,用于接收topic消息,不配置的话,默认接收queue队列消息
* @param @return
* @return DefaultJmsListenerContainerFactory
* @throws
*/
@Bean
public DefaultJmsListenerContainerFactory topicFactory(){
DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory();
factory.setConnectionFactory(connectionFactory);
//PubSubDomain代表模式, true:发布/订阅模式,即topic , false:点对点模式,即queue
factory.setPubSubDomain(true);
return factory;
}
}
这里说明一下,使用@JmsListener这个注解的时候。需要在配置类上加上@EnableJms并且要配置一个DefaultJmsListenerContainerFactory监听容器工厂,在@JmsListener(destination="XX", containerFactory="引入工厂"),如果不引入会出现监听不了topic的消息的问题,后面分析。
5. 编写一个启动类
package com.hik.hyy.jms.bootMQ;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
@SpringBootApplication
public class Application1 {
public static void main(String[] args) {
SpringApplication.run(Application1.class, args);
}
}
这个启动类配合@SpringBootTest注解使用,在这也踩了个坑!!!
6. 编写测试类
package com.hik.hyy.jms.bootMQ;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
import javax.jms.TextMessage;
import org.apache.activemq.command.ActiveMQQueue;
import org.apache.activemq.command.ActiveMQTopic;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application1.class, webEnvironment = SpringBootTest.WebEnvironment.NONE)
public class ActiveMQTest {
//加载模板类
@Autowired
private JmsTemplate jmsTemplate;
@Autowired
private ActiveMQQueue queue;
@Autowired
private ActiveMQTopic topic;
/**
* @Description: 队列消息生产者
* @param @throws Exception
* @return void
* @date: 2018年9月26日 下午4:22:43
* @throws
*/
@Test
public void testQueueProducer() throws Exception{
System.out.println(queue.getQueueName());
for (int i = 0; i < 5; i++) { //生产消息
jmsTemplate.send(queue, new MessageCreator() {
@Override
public Message createMessage(Session session) throws JMSException {
TextMessage message = session.createTextMessage("hello,this is a queueMessage");
return message;
}
});
// jmsTemplate.convertAndSend(queue, "hello,this is a queueMessage" + i);
Thread.sleep(500);
}
}
/**
* @Description: 主题消息生产者
* @param @throws Exception
* @return void
* @date: 2018年9月26日 下午4:23:13
* @throws
*/
@Test
public void testTopicProducer() throws Exception{
System.err.println(topic.getTopicName());
for (int i = 0; i < 5; i++) { //生产5条消息
//方式一
// jmsTemplate.send(topic, new MessageCreator() {
//
// @Override
// public Message createMessage(Session session) throws JMSException {
// TextMessage message = session.createTextMessage("hello,this is a topicMessage");
// return message;
// }
// });
//方式二
jmsTemplate.convertAndSend(topic, "hello,this is a topicMessage" + i);
}
System.in.read();
}
}
@SpringBootTest(classes = Application1.class, webEnvironment = SpringBootTest.WebEnvironment.NONE),解释下这个注解里面的配置,classes加载我们刚才的启动项,SpringBootTest.WebEnvironment.RANDOM_PORT经常和测试类中@LocalServerPort
一起在注入属性时使用,结果会随机生成一个端口号。
7. 结果
7.1 queue,运行testQueueProducer()方法:
7.2 topic,运行testTopicProducer()方法
8. 坑
修改监听topic的@JmsListener注解
/**
* @Description: topic消费者
*/
@JmsListener(destination = "topic1")
public void topicMessage1(Message message){
try {
TextMessage message2 = (TextMessage) message;
System.err.println("topic1收到的消息:" + message2.getText());
} catch (Exception e) {
e.printStackTrace();
}
}
@JmsListener(destination = "topic1")
public void topicMessage2(String message){
System.err.println("topic2收到的消息:" + message);
}
再运行testTopicProducer()方法,我们会发现这两个topic消费者并未消费任何消息,而是去监听了一个叫“topic1”的queue:
简单分析@JmsListener的源码: