SpringBoot中使用AMQ的兩種方式二(Java配置、註解方式)
使用@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的原始碼: