SpringBoot中使用AMQ的两种方式二(Java配置、注解方式)

                                       使用@JmsListener注解方式

1. 工程目录

                                                                      SpringBoot中使用AMQ的两种方式二(Java配置、注解方式)_第1张图片          

2. 引入依赖



	4.0.0

	com.hik.hyy
	spring-boot
	0.0.1-SNAPSHOT
	jar

	spring-boot
	Demo project for Spring Boot

	
		org.springframework.boot
		spring-boot-starter-parent
		1.5.8.RELEASE
		 
	

	
		UTF-8
		UTF-8
		1.8
	

	
		
			org.springframework.boot
			spring-boot-starter-activemq
		

		
			org.springframework.boot
			spring-boot-starter-test
			test
		
	

	
		
			
				org.springframework.boot
				spring-boot-maven-plugin
			
		
	



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()方法:

SpringBoot中使用AMQ的两种方式二(Java配置、注解方式)_第2张图片

               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:

SpringBoot中使用AMQ的两种方式二(Java配置、注解方式)_第3张图片

       简单分析@JmsListener的源码:

SpringBoot中使用AMQ的两种方式二(Java配置、注解方式)_第4张图片

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

你可能感兴趣的:(AMQ)