基础知识

  1. 虚拟主机 (Virtual Host): 每个 virtual host 拥有自己的 exchanges, queues 等 (类似 MySQL 中的库)
  2. 交换器 (Exchange): 生产者产生的消息并不是直接发送给 queue 的,而是要经过 exchange 路由, exchange 类型如下:
    1. fanout: 把所有发送到该 exchange 的消息路由到所有与它绑定的 queue 中
    2. direct: 把消息路由到 binding key 与routing key 完全匹配的 queue 中
    3. topic: 模糊匹配 (单词间使用”.”分割,”*” 匹配一个单词,”#” 匹配零个或多个单词)
    4. headers: 根据发送的消息内容中的 headers 属性进行匹配
  3. 信道 (Channel): 建立在真实的 TCP 连接之上的虚拟连接, RabbitMQ 处理的每条 AMQP 指令都是通过 channel 完成的

使用示例

RabbitMQ 安装参考: docker 安装rabbitMQ

新建 Spring Boot 项目,添加配置:

spring:
rabbitmq:
host: 192.168.30.101
port: 5672
username: admin
password: admin
virtual-host: my_vhost logging:
level:
com: INFO

1. 基本使用

Queue

@Configuration
public class RabbitmqConfig { @Bean
public Queue hello() {
return new Queue("hello");
} }

Producer

@Component
@EnableAsync
public class SenderTask { private static final Logger logger = LoggerFactory.getLogger(SenderTask.class); @Autowired
private RabbitTemplate rabbitTemplate; @Autowired
private Queue queue; @Async
@Scheduled(cron = "0/1 * * * * ? ")
public void send(){
String message = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); rabbitTemplate.convertAndSend(queue.getName(), message); logger.info(" [x] Sent '" + message + "'");
}
}

Consumer

@Component
@RabbitListener(queues = "hello")
public class ReceiverTask { private static final Logger logger = LoggerFactory.getLogger(ReceiverTask.class); @RabbitHandler
public void receive(String in){
logger.info(" [x] Received '" + in + "'");
}
}

2. fanout

Exchange, Queue, Binding

@Configuration
public class RabbitmqConfig { @Bean
public FanoutExchange fanout() {
return new FanoutExchange("fanoutExchangeTest");
} @Bean
public Queue autoDeleteQueue1() {
return new AnonymousQueue();// 创建一个非持久的,独占的自动删除队列
} @Bean
public Queue autoDeleteQueue2() {
return new AnonymousQueue();
} @Bean
public Binding binding1(FanoutExchange fanout,
Queue autoDeleteQueue1) {
return BindingBuilder.bind(autoDeleteQueue1).to(fanout);
} @Bean
public Binding binding2(FanoutExchange fanout,
Queue autoDeleteQueue2) {
return BindingBuilder.bind(autoDeleteQueue2).to(fanout);
}
}

Producer

@Component
@EnableAsync
public class SenderTask { private static final Logger logger = LoggerFactory.getLogger(SenderTask.class); @Autowired
private RabbitTemplate rabbitTemplate; @Autowired
private FanoutExchange fanoutExchange; @Async
@Scheduled(cron = "0/1 * * * * ? ")
public void send(){
String message = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); rabbitTemplate.convertAndSend(fanoutExchange.getName(), "", message); logger.info(" [x] Sent '" + message + "'");
}
}

Consumer

@Component
public class ReceiverTask { private static final Logger logger = LoggerFactory.getLogger(ReceiverTask.class); @RabbitListener(queues = "#{autoDeleteQueue1.name}")
public void receive1(String in){
receive(in, 1);
} @RabbitListener(queues = "#{autoDeleteQueue2.name}")
public void receive2(String in){
receive(in, 2);
} public void receive(String in, int receiver){
logger.info("instance " + receiver + " [x] Received '" + in + "'");
}
}

3. direct

Exchange, Queue, Binding

@Configuration
public class RabbitmqConfig { @Bean
public DirectExchange direct() {
return new DirectExchange("directExchangeTest");
} @Bean
public Queue autoDeleteQueue1() {
return new AnonymousQueue();// 创建一个非持久的,独占的自动删除队列
} @Bean
public Queue autoDeleteQueue2() {
return new AnonymousQueue();
} @Bean
public Binding binding1a(DirectExchange direct,
Queue autoDeleteQueue1) {
return BindingBuilder.bind(autoDeleteQueue1).to(direct).with("orange");
} @Bean
public Binding binding1b(DirectExchange direct,
Queue autoDeleteQueue1) {
return BindingBuilder.bind(autoDeleteQueue1).to(direct).with("green");
} @Bean
public Binding binding2a(DirectExchange direct,
Queue autoDeleteQueue2) {
return BindingBuilder.bind(autoDeleteQueue2).to(direct).with("green");
} @Bean
public Binding binding2b(DirectExchange direct,
Queue autoDeleteQueue2) {
return BindingBuilder.bind(autoDeleteQueue2).to(direct).with("black");
}
}

Producer

@Component
@EnableAsync
public class SenderTask { private static final Logger logger = LoggerFactory.getLogger(SenderTask.class); @Autowired
private RabbitTemplate rabbitTemplate; @Autowired
private DirectExchange directExchange; private final String[] keys = {"orange", "black", "green"}; @Async
@Scheduled(cron = "0/1 * * * * ? ")
public void send(){ Random random = new Random(); String key = keys[random.nextInt(keys.length)]; String message = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))
+ " to: " + key; rabbitTemplate.convertAndSend(directExchange.getName(), key, message); logger.info(" [x] Sent '" + message + "'");
}
}

Consumer

@Component
public class ReceiverTask { private static final Logger logger = LoggerFactory.getLogger(ReceiverTask.class); @RabbitListener(queues = "#{autoDeleteQueue1.name}")
public void receive1(String in){
receive(in, 1);
} @RabbitListener(queues = "#{autoDeleteQueue2.name}")
public void receive2(String in){
receive(in, 2);
} public void receive(String in, int receiver){
logger.info("instance " + receiver + " [x] Received '" + in + "'");
}
}

4. topic

Exchange, Queue, Binding

@Configuration
public class RabbitmqConfig { @Bean
public TopicExchange topic() {
return new TopicExchange("topicExchangeTest");
} @Bean
public Queue autoDeleteQueue1() {
return new AnonymousQueue();// 创建一个非持久的,独占的自动删除队列
} @Bean
public Queue autoDeleteQueue2() {
return new AnonymousQueue();
} @Bean
public Binding binding1a(TopicExchange topic,
Queue autoDeleteQueue1) {
return BindingBuilder.bind(autoDeleteQueue1).to(topic).with("*.orange.*");
} @Bean
public Binding binding1b(TopicExchange topic,
Queue autoDeleteQueue1) {
return BindingBuilder.bind(autoDeleteQueue1).to(topic).with("*.*.rabbit");
} @Bean
public Binding binding2a(TopicExchange topic,
Queue autoDeleteQueue2) {
return BindingBuilder.bind(autoDeleteQueue2).to(topic).with("lazy.#");
} }

Producer

@Component
@EnableAsync
public class SenderTask { private static final Logger logger = LoggerFactory.getLogger(SenderTask.class); @Autowired
private RabbitTemplate rabbitTemplate; @Autowired
private TopicExchange topicExchange; private final String[] keys = {"quick.orange.rabbit", "lazy.orange.elephant", "quick.orange.fox",
"lazy.brown.fox", "lazy.pink.rabbit", "quick.brown.fox"}; @Async
@Scheduled(cron = "0/1 * * * * ? ")
public void send(){ Random random = new Random(); String key = keys[random.nextInt(keys.length)]; String message = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))
+ " to: " + key; rabbitTemplate.convertAndSend(topicExchange.getName(), key, message); logger.info(" [x] Sent '" + message + "'");
}
}

Consumer

@Component
public class ReceiverTask { private static final Logger logger = LoggerFactory.getLogger(ReceiverTask.class); @RabbitListener(queues = "#{autoDeleteQueue1.name}")
public void receive1(String in){
receive(in, 1);
} @RabbitListener(queues = "#{autoDeleteQueue2.name}")
public void receive2(String in){
receive(in, 2);
} public void receive(String in, int receiver){
logger.info("instance " + receiver + " [x] Received '" + in + "'");
}
}

完整代码:GitHub

Spring Boot + RabbitMQ 使用示例的更多相关文章

  1. Spring boot+RabbitMQ环境

    Spring boot+RabbitMQ环境 消息队列在目前分布式系统下具备非常重要的地位,如下的场景是比较适合消息队列的: 跨系统的调用,异步性质的调用最佳. 高并发问题,利用队列串行特点. 订阅模 ...

  2. spring boot Rabbitmq集成,延时消息队列实现

    本篇主要记录Spring boot 集成Rabbitmq,分为两部分, 第一部分为创建普通消息队列, 第二部分为延时消息队列实现: spring boot提供对mq消息队列支持amqp相关包,引入即可 ...

  3. 从头开始搭建一个Spring boot+RabbitMQ环境

    *:first-child { margin-top: 0 !important; } body>*:last-child { margin-bottom: 0 !important; } /* ...

  4. spring boot 入门及示例

    需要环境:eclipse4.7.3 + jdk1.8 +maven3.6.1 + tomcat(web需要) spring boot官网介绍:https://spring.io/guides/gs/s ...

  5. Spring Boot Jersey使用示例

    前言 本文将学习如何使用Spring Boot和Jersey框架,去配置和创建JAX-RS 2.0 REST API接口: 这个示例应用使用的是Jersey的Servlet容器去部署REST API接 ...

  6. spring boot +RabbitMQ +InfluxDB+Grafara监控实践

    本文需要有相关spring boot 或spring cloud 相关微服务框架的基础,如果您具备相关基础可以很容易的实现下述过程!!!!!!! 希望本文的所说对需要的您有所帮助 从这里我们开始进入闲 ...

  7. spring boot rabbitmq 多MQ配置 自动 创建 队列 RPC

      源码地址:https://github.com/hutuchong518/RabbitmqStudy 需求:   spring boot 整合 rabbitmq rpc功能, 需要将 请求和响应 ...

  8. Spring Boot RabbitMQ 延迟消息实现完整版

    概述 曾经去网易面试的时候,面试官问了我一个问题,说 下完订单后,如果用户未支付,需要取消订单,可以怎么做 我当时的回答是,用定时任务扫描DB表即可.面试官不是很满意,提出: 用定时任务无法做到准实时 ...

  9. Spring Boot + RabbitMQ 配置参数解释

    最近生产RabbitMQ出了几次问题,所以抽时间整理了一份关于Spring Boot 整合RabbitMQ环境下的配置参数解释,通过官网文档和网上其他朋友一些文章参考归纳整理而得,有错误之处还请指正~ ...

随机推荐

  1. 《Google软件测试之道》 第一章google软件测试介绍

    前段时间比较迷茫,没有明确的学习方向和内容.不过有一点应该是可以肯定的:迷茫的时候就把空闲的时间用来看书吧! 这本书,目前只是比较粗略的看了一遍,感触很大.以下是个人所作的笔记,与原文会有出入的地方. ...

  2. Python如何快速复制序列?

    1 基本用法 把序列乘以一个整数,就会产生一个新序列.这个新序列是原始序列复制了整数份,然后再拼接起来的结果. l=[1,2,3] l2=l * 3 logging.info('l2 -> %s ...

  3. js常用的遍历方法以及flter,map方法

    1.首先明确vue主要操作数据.他并不提倡操作dom. 数组的变异:能改变原数组. *** 先来复习下便利==遍历一个数组的四种方法: <script> let arr = [1, 2, ...

  4. JS缓冲运动案例:右下角悬浮窗

    JS缓冲运动案例:右下角悬浮窗 红色区块模拟页面的右下角浮窗,在页面进行滚动时,浮窗做缓冲运动,最终在页面右下角停留. <!DOCTYPE html> <html lang=&quo ...

  5. MCscan-Python-jcvi 共线性画图最后一章更新

    经过几轮调试和修改,共线性图终于可以上眼了.如下: 图中红色的为目标基因,蓝色的为reference species目标基因周围15个基因,天蓝色为再往外15个基因,黄色为与reference spe ...

  6. linux 进程间通信 共享内存 mmap

    共享内存可以说是最有用的进程间通信方式,也是最快的IPC形式.两个不同进程A.B共享内存的意思是,同一块物理内存被映射到进程A.B各自的进程地址空间.进程A可以即时看到进程B对共享内存中数据的更新,反 ...

  7. 测试:OGG初始化同步表,源端抽取进程scn<源端事务的start_scn时,这个变化是否会同步到目标库中?

    一.测试目标 疑问,OGG初始化同步表,源端抽取进程开始抽取的scn<源端事务的start_scn时,这个变化是否会同步到目标库中? 二.实验测试 如下进行测试! session 1 SQL&g ...

  8. Spring源码之AbstractApplicationContext中refresh方法注释

    https://blog.csdn.net/three_stand/article/details/80680004 refresh() prepareRefresh(beanFactory) 容器状 ...

  9. 2w+长文带你剖析ConcurrentHashMap~!

    并发编程实践中,ConcurrentHashMap是一个经常被使用的数据结构,相比于Hashtable以及Collections.synchronizedMap(),ConcurrentHashMap ...

  10. Win7 安装 Docker 踩的那些坑

    公司电脑是 WIN7 x64 旗舰版 SP1,安装 Docker 时踩了好多雷,分享出来给大家排排雷. 首先,Docker Desktop Installer 的 Windows 版只支持 Win10 ...