使用@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自己配置的连接工厂@AutowiredConnectionFactory connectionFactory;/** * @Description:  创建queue*/@Beanpublic ActiveMQQueue queueDestination() {return new ActiveMQQueue("queue1");}/** * @Description:  创建topic*/@Beanpublic ActiveMQTopic topicDestination(){return new ActiveMQTopic("topic1");}/** * @Description:  使用@JmsListener注解时,用于接收topic消息,不配置的话,默认接收queue队列消息* @param @return    * @return DefaultJmsListenerContainerFactory* @throws */@Beanpublic DefaultJmsListenerContainerFactory topicFactory(){DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory();factory.setConnectionFactory(connectionFactory);//PubSubDomain代表模式, true:发布/订阅模式,即topic , false:点对点模式,即queuefactory.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 {//加载模板类@Autowiredprivate JmsTemplate jmsTemplate;@Autowiredprivate ActiveMQQueue queue;@Autowiredprivate ActiveMQTopic topic;/** * @Description:  队列消息生产者* @param @throws Exception    * @return void* @date: 2018年9月26日 下午4:22:43  * @throws */@Testpublic void testQueueProducer() throws Exception{System.out.println(queue.getQueueName());for (int i = 0; i < 5; i++) { //生产消息jmsTemplate.send(queue, new MessageCreator() {@Overridepublic 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 */@Testpublic 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的源码:

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

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

    Java配置方式使用AMQ 1. 引入依赖(pom.xml) <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns ...

  2. JAVA配置注解方式搭建简单的SpringMVC前后台交互系统

    前面两篇文章介绍了 基于XML方式搭建SpringMVC前后台交互系统的方法,博文链接如下: http://www.cnblogs.com/hunterCecil/p/8252060.html htt ...

  3. Springboot中数据库访问的两种方式之-JdbcTemplate

    目录 01.写在前面 02.项目依赖 03.创建模型脚本 04.读取数据库 05.Controller 06.开始测试 本文由bingo创作,授权我原创发布. Tiger和他朋友们的原创技术文章,请关 ...

  4. reportConfig.xml两种数据源连接的配置方式

     在reportConfig.xml配置文件中,我们提供了两种数据源连接的配置方式,分别如下: 1.jndi数据源配置(即:在dataSource中配置) 此配置适用于在j2ee的服务器中配置了j ...

  5. SpringBoot文件访问映射的两种实现方式

    SpringBoot文件访问映射的两种实现方式 业务需求:通过SpringBoot访问服务器(磁盘内)的所有文件,用于正常项目中上传图片(文件)的访问. 图片路径:E://images/upload/ ...

  6. 实验四:使用库函数API和C代码中嵌入汇编代码两种方式使用同一个系统调用

    贺邦+原创作品转载请注明出处 + <Linux内核分析>MOOC课程http://mooc.study.163.com/course/USTC-1000029000 实验目的: 使用库函数 ...

  7. TF之RNN:TF的RNN中的常用的两种定义scope的方式get_variable和Variable

    TF之RNN:TF的RNN中的常用的两种定义scope的方式get_variable和Variable 目录 输出结果 代码设计 输出结果 代码设计 # tensorflow中的两种定义scope(命 ...

  8. Java中HashMap遍历的两种方式

    第一种: Map map = new HashMap(); Iterator iter = map.entrySet().iterator(); while (iter.hasNext()) { Ma ...

  9. java map遍历_Java中Map集合的两种遍历方式

    Java中的map遍历有多种方法,从最早的Iterator,到java5支持的foreach,再到java8 Lambda,让我们一起来看下Java中Map集合的两种遍历方式! 关于遍历Map集合的几 ...

最新文章

  1. 跟面向对象卯上了,看看ES6的“类”
  2. Mac上搭建直播服务器Nginx+rtmp
  3. 近期活动盘点:2019清华大数据系统软件峰会(9.15)
  4. python学习手册笔记——20.迭代和解析
  5. java面试题(开发框架)
  6. 计算机科学概论ppt免费,计算机科学概论(第9版)Lecture_slide07.ppt
  7. 一种简单定义FourCC常量的方法 (C/C++)
  8. [学习笔记] 如果你愿意学那么你是可以看的懂的 —— 群论与 burnside 引理和 polya 定理
  9. python123第七章_Python入门第7/10页
  10. jsp中设置自动换行_办公技巧—Word中如何设置自动生成序号
  11. java中子类与父类中隐含的this引用的分析
  12. 分布式Tensorflow入门Demo
  13. 计组之指令系统:3、CISC和RISC
  14. 【jQuery笔记Part2】02-jQuery展开收起动画帷幔效果案例下拉菜单案例显示隐藏更多案例折叠菜单案例
  15. VLC框架总结(二)VLC源码及各modules功能介绍
  16. 【路径规划】基于matlab GUI A_star算法最短路径规划【含Matlab源码 633期】
  17. 农夫山泉下场当“烧水工”,熟水市场是“鸡肋”还是“机遇”?
  18. 判断char*是否为utf8编码
  19. Matlab按照二进制读写txt文件
  20. 横向数据(按行)的最大值和最小值的SQL语句的编写 !

热门文章

  1. 笔记本建立wifi热点
  2. 傻瓜式搭建私人网盘-有手就行
  3. 【渝粤教育】国家开放大学2018年秋季 0195-21T机械设计基础 参考试题
  4. php怎么字符串转成json对象_php中json字符串转换为对象?
  5. 遇到Host ‘xxx’ is not allowed to connet to this MySQL server 问题
  6. 时间序列及其R代码实现
  7. 中科蓝讯-库文件的选择
  8. OpenCV OCR实战 文档扫描与文字检测
  9. 快递企业下一步:国际化、多元化,发展科技提升竞争力
  10. 吃鸡用什么游戏蓝牙耳机?适合吃鸡用的低延迟蓝牙耳机推荐