在实际开发中我们需要监听场景,比如我们之前举的例子,两个系统,订单系统,和我们库存系统,他们交互都是通过交互通过消息队列,某一个人下了单以后,将订单信息放到消息队列中,库存系统要实时监听队列里的内容,一旦有新的订单进来,库存系统就要负责相关的操作,那我们的监听怎么写呢,Spring为了简化我么开发,给我们引入了相关的注解,比如我们来举一个例子,我来写一个BookService,就来监听book里面的内容,我怎么写呢,我就叫receive,在这方法里面呢,我们要收到book的内容,所以我在方法的参数上,我们这个方法是通过监听消息队列,可以来写一个注解,@RabbitListener,监听MQ的,那监听哪个消息队列呢,我们可以来写一个queues,这个queues它是一个数组的方式,/*** The queues for this listener.* The entries can be 'queue name', 'property-placeholder keys' or 'expressions'.* Expression must be resolved to the queue name or {@code Queue} object.* Mutually exclusive with {@link #bindings()}* @return the queue names or expressions (SpEL) to listen to from target* {@link org.springframework.amqp.rabbit.listener.MessageListenerContainer}.*/
String[] queues() default {};我们可以监听多个消息队列,我们就来监听我们之前的china.news,我们就来监听,有内容进来,@EnableRabbit,开启基于注解的MQ
package com.learn.service;import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;import com.learn.bean.Book;@Service
public class BookService {@RabbitListener(queues="china.news")public void receive(Book book) {System.out.println("收到消息" + book);}}
package com.learn;import org.springframework.amqp.rabbit.annotation.EnableRabbit;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;/*** 自动配置* @author Leon.Sun**/
@SpringBootApplication
@EnableRabbit
public class SpringBoot02AmqpApplication {public static void main(String[] args) {// Spring应用启动起来SpringApplication.run(SpringBoot02AmqpApplication.class,args);}}
有了这两个注解的配合,让@RabbitListener来监听Listener里的内容,监听消息队列的内容,我们就来启动一下这个应用,来测试一下,只要有book信息来,我们就会收到,一启动就收到消息收到消息Book [bookName=三国演义, author=罗贯中]/*** 广播*/
@Test
public void sendMsg() {rabbitTemplate.convertAndSend("exchange.fanout","",new Book("红楼梦","曹雪芹"));
}收到消息Book [bookName=红楼梦, author=曹雪芹]这就是我们收到消息监听来收消息,只要消息队列里有,这个我们直接序列化成Book对象,如果我们有一些定制的消息,还想要消息头等等,写成Message类型org.springframework.amqp.core.Message写上Message类型以后呢,我们来写一个@RabbitListener,我们来监听china队列,我们写的Message参数,既有getBody消息的内容,还有getMessageProperties,我们消息的头信息,我们可以重新尝试一下,我们来到这个主程序,他重新启动,来看china里的内容,china默认已经有两个内容了,我们启动的时候都能收到,[B@4511a7ef
MessageProperties [headers={__TypeId__=com.learn.bean.Book}, timestamp=null, messageId=null,
userId=null,
receivedUserId=null, appId=null, clusterId=null, type=null, correlationId=null,
correlationIdString=null,
replyTo=null, contentType=application/json, contentEncoding=UTF-8, contentLength=0,
deliveryMode=null,
receivedDeliveryMode=PERSISTENT, expiration=null, priority=0, redelivered=false,
receivedExchange=exchange.fanout, receivedRoutingKey=, receivedDelay=null, deliveryTag=1,
messageCount=0,
consumerTag=amq.ctag-jmwvhNiVfS6HYqKWi5xuCw, consumerQueue=china]
[B@71e6aae7
MessageProperties [headers={__TypeId__=com.learn.bean.Book}, timestamp=null, messageId=null,
userId=null,
receivedUserId=null, appId=null, clusterId=null, type=null, correlationId=null,
correlationIdString=null,
replyTo=null, contentType=application/json, contentEncoding=UTF-8, contentLength=0,
deliveryMode=null,
receivedDeliveryMode=PERSISTENT, expiration=null, priority=0, redelivered=false,
receivedExchange=exchange.fanout, receivedRoutingKey=, receivedDelay=null,
deliveryTag=2,messageCount=0, consumerTag=amq.ctag-jmwvhNiVfS6HYqKWi5xuCw, consumerQueue=china]
package com.learn.service;import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;import com.learn.bean.Book;@Service
public class BookService {@RabbitListener(queues="china.news")public void receive(Book book) {System.out.println("收到消息" + book);}@RabbitListener(queues="china")public void receive02(Message message) {System.out.println(message.getBody());System.out.println(message.getMessageProperties());}
}
package com.learn;import org.springframework.amqp.rabbit.annotation.EnableRabbit;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;/*** 自动配置* @author Leon.Sun**/
@SpringBootApplication
@EnableRabbit
public class SpringBoot02AmqpApplication {public static void main(String[] args) {// Spring应用启动起来SpringApplication.run(SpringBoot02AmqpApplication.class,args);}}
package com.learn.springboot;import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;import com.learn.bean.Book;@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBootAmqpApplicationTests {@AutowiredRabbitTemplate rabbitTemplate;/*** 1.单播(点对点)*/@Testpublic void contextLoads() {// Message需要自己构造一个,定义消息体内容和消息头
//      rabbitTemplate.send(exchange, routingKey, message);// object默认当成消息体,只需要传入要发送的对象,自动序列化发送给rabbitmq
//      rabbitTemplate.convertAndSend(routingKey, message, messagePostProcessor);Map<String,Object> map = new HashMap<String,Object>();map.put("msg", "这是第一个消息");map.put("data", Arrays.asList("helloworld",1231,true));       // 对象被默认序列化以后发送出去rabbitTemplate.convertAndSend("exchange.direct", "china.news",new Book("西游记","吴承恩"));}@Testpublic void receive() {Object o = rabbitTemplate.receiveAndConvert("china.news");System.out.println(o.getClass());System.out.println(o);}/*** 广播*/@Testpublic void sendMsg() {rabbitTemplate.convertAndSend("exchange.fanout","",new Book("红楼梦","曹雪芹"));}
}

SpringBoot高级-消息-@RabbitListener@EnableRabbit相关推荐

  1. SpringBoot高级-消息-JMSAMQP简介

    我们来学习SpringBoot和消息,SpringBoot与消息队列的整合使用,包括消息队列的两个常见规范,JMS Java消息服务,和AMQP,高级消息队列协议,而且我们还会整合RabbitMQ来使 ...

  2. springboot高级——消息队列相关

    写在前边:本文学习尚硅谷的springboot高级整理笔记. 消息队列是什么,有什么好处? 我们可以把消息队列比作是一个存放消息的容器,当我们需要使用消息的时候可以取出消息供自己使用.消息队列是分布式 ...

  3. SpringBoot高级消息-RabbitMQ运行机制

    RabbitMQ的核心运行机制,首先在我们高级消息队列的路由机制,这个和JMS是有大差别的,他给我们增加了Exchange和Bindding,Exchange就是我们介绍的交换器,和Binding绑定 ...

  4. SpringBoot高级-消息-AmqpAdmin管理组件的使用

    前提是消息队列和exchanges创建好了,如果没有创建好,我们程序重要怎么去创建这些呢,我们就可以使用一个组件,叫AmqpAdmin,因为我们要使用程序临时的创建一些,绑定规则,或者创建一些消息队列 ...

  5. SpringBoot高级-消息-RabbitTemplate发送接受消息序列化机制

    引入了spring-boot-starter-amqp模块,他引入了spring-messaging模块,包括引入了spring-rabbit模块,怎么配置使用呢,<dependency> ...

  6. SpringBoot高级-消息-RabbitMQ安装测试

    docker imagesdocker ps -adocker pull registry.docker-cn.com/library/rabbitmq:3-managementregistry.do ...

  7. SpringBoot高级特性

    SpringBoot高级特性 SpringBoot缓存 基本环境搭建 导入数据库文件,创建出 department 和 employee 数据表 创建 JavaBean 封装数据 整合 Mybatis ...

  8. SpringBoot高级教程

    SpringBoot的高级教程 一.SpringBoot缓存 缓存的场景 临时性数据存储[校验码] 避免频繁因为相同的内容查询数据库[查询的信息] 1.JSR107缓存规范 用的比较少 Java Ca ...

  9. springboot高级篇及springboot1.5转springboot2.17所遇到的坑

    SpringBoot的高级教程 一.SpringBoot缓存 缓存的场景 临时性数据存储[校验码] 避免频繁因为相同的内容查询数据库[查询的信息] 1.JSR107缓存规范 用的比较少 Java Ca ...

最新文章

  1. 清华男女图鉴 | 有电车会拍照,我在清华还是找不到女朋友
  2. HBase 创建表/插入数据/查询数据命令
  3. Docker+Jenkins+Git+GitLab实现DevOps
  4. C语言中的数组的使用——混乱的内存管理
  5. 直方图(信息学奥赛一本通-T1115)
  6. 移动端点击链接元素出现蓝色边框或者出现半透明蓝色背景
  7. mysql服务器是否支持tcp/ip连接,(3)MySQL客户端与服务端的TCP/IP及socket连接方式-Go语言中文社区...
  8. linux 多CPU
  9. CentOS 7下基于bitnami的Redmine结合Subversion的设置
  10. pyinstaller使用-python项目转换成exe可执行文件
  11. IDL size函数
  12. 用canvas画圆饼图
  13. Java 验证码识别(1)使用 Tess4J 进行 OCR 识别
  14. 回顾 | Tencent Serverless Hours 线上分享会第一期
  15. 小米MIUI开发版应用闪退问题 Secure.ANDROID_ID must not be null
  16. iOS 直播 —— 推流
  17. 年货来咯:精选年度最受欢迎干货,覆盖客户端、服务端、前端、数据、算法……...
  18. python 实现udp通信
  19. 丢手帕问题(约瑟夫问题)
  20. 手机短信真的可信吗# 传统短信伪造攻击的可能性证明

热门文章

  1. delphi 中配置文件的使用(*.ini)
  2. 使用SQL Server 2005 Report Builder
  3. Mysql表分区的选择与实践小结
  4. python学习六:数据结构
  5. java 中Lock的使用
  6. Linux学习—vim大全
  7. C#通过Redis实现分布式锁
  8. 探索 OpenStack 之(10):深入镜像服务Glance
  9. 指针数组,数组指针,函数指针,main函数实质,二重指针,函数指针作为參数,泛型函数...
  10. CSharpGL(36)通用的非托管数组排序方法