• 【初始RabbitMQ】延迟队列的实现


    延迟队列概念

    延迟队列中的元素是希望在指定时间到了之后或之前取出和处理消息,并且队列内部是有序的。简单来说,延时队列就是用来存放需要在指定时间被处理的元素的队列

    延迟队列使用场景

    延迟队列经常使用的场景有以下几点:

    1. 订单在十分钟之内未支付则自动取消
    2. 新创建的店铺,如果在十天内都没有上传过商品,则自动发送消息提醒
    3. 用户注册成功后,如果三天内没有登陆则进行短信提醒
    4. 用户发起退款,如果三天内没有得到处理则通知相关运营人员
    5. 预定会议后,需要在预定的时间点前十分钟通知各个与会人员参加会议

    这些场景都有一个特点,需要在某个事件发生之后或者之前的指定时间点完成某一项任务,如: 发生订单生成事件,在十分钟之后检查该订单支付状态,然后将未支付的订单进行关闭;看起来似乎 使用定时任务,一直轮询数据,每秒查一次,取出需要被处理的数据,然后处理不就完事了吗?如果 数据量比较少,确实可以这样做,比如:对于“如果账单一周内未支付则进行自动结算”这样的需求, 如果对于时间不是严格限制,而是宽松意义上的一周,那么每天晚上跑个定时任务检查一下所有未支 付的账单,确实也是一个可行的方案。但对于数据量比较大,并且时效性较强的场景,如:“订单十 分钟内未支付则关闭“,短期内未支付的订单数据可能会有很多,活动期间甚至会达到百万甚至千万 级别,对这么庞大的数据量仍旧使用轮询的方式显然是不可取的,很可能在一秒内无法完成所有订单 的检查,同时会给数据库带来很大压力,无法满足业务要求而且性能低下

    RabbitMQ中的TTL

    TTL表示RabbitMQ中的一个消息或者队列的属性,表明一条消息或者该队列中所有消息的最大存活时间,单位是毫秒。换句话说,如果一条消息设置了 TTL 属性或者进入了设置 TTL 属性的队列,那么这 条消息如果在 TTL 设置的时间内没有被消费,则会成为"死信"。如果同时配置了队列的 TTL 和消息的 TTL,那么较小的那个值将会被使用     

    消息设置TTL             

    1. rabbitTemplate.convertAndSend(
    2. "myExchange", // 交换机名称
    3. "XC", // 路由键
    4. message,
    5. correlationData -> {
    6. // 设置消息的 TTL
    7. correlationData.getMessageProperties().setExpiration(String.valueOf(ttlTime));
    8. return correlationData;
    9. }
    10. );

    队列设置TTL

    1. Map args = new HashMap<>();
    2. args.put("x-message-ttl", 60000); // 设置队列中所有消息的TTL为60秒
    3. return new Queue("myQueue", true, false, false, args);

    两者区别

    如果设置了队列的 TTL 属性,那么一旦消息过期,就会被队列丢弃(如果配置了死信队列被丢到死信队 列中),而第二种方式,消息即使过期,也不一定会被马上丢弃,因为消息是否过期是在即将投递到消费者之前判定的,如果当前队列有严重的消息积压情况,则已过期的消息也许还能存活较长时间;另外,还需要注意的一点是,如果不设置 TTL,表示消息永远不会过期,如果将 TTL 设置为 0,则表示除非此时可以 直接投递该消息到消费者,否则该消息将会被丢弃

    整合SpringBoot

    创建项目

    添加依赖

    1. "1.0" encoding="UTF-8"?>
    2. "http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    4. 4.0.0
    5. org.springframework.boot
    6. spring-boot-starter-parent
    7. 3.2.2
    8. com.example
    9. springboot-rabbitmq
    10. 0.0.1-SNAPSHOT
    11. demo
    12. Demo project for Spring Boot
    13. 17
    14. org.springframework.boot
    15. spring-boot-starter-amqp
    16. org.springframework.boot
    17. spring-boot-starter-web
    18. org.projectlombok
    19. lombok
    20. true
    21. org.springframework.boot
    22. spring-boot-starter-test
    23. test
    24. org.springframework.amqp
    25. spring-rabbit-test
    26. test
    27. org.springframework.boot
    28. spring-boot-maven-plugin

     修改配置文件

    1. spring.rabbitmq.host=118.31.6.132
    2. spring.rabbitmq.port=5672
    3. spring.rabbitmq.username=admin
    4. spring.rabbitmq.password=123

    队列TTL

    代码架构图

    创建两个队列 QA 和 QB,两者队列 TTL 分别设置为 10S 和 40S,然后在创建一个交换机 X 和死信交 换机 Y,它们的类型都是 direct,创建一个死信队列 QD,它们的绑定关系如下:

    配置文件类代码

    1. package com.example.demo.config;
    2. import org.springframework.amqp.core.*;
    3. import org.springframework.beans.factory.annotation.Qualifier;
    4. import org.springframework.context.annotation.Bean;
    5. import org.springframework.context.annotation.Configuration;
    6. import java.util.HashMap;
    7. import java.util.Map;
    8. @Configuration
    9. public class TtlQueueConfig {
    10. public static final String X_EXCHANGE = "X";
    11. public static final String QUEUE_A = "QA";
    12. public static final String QUEUE_B = "QB";
    13. public static final String Y_DEAD_LETTER_EXCHANGE = "Y";
    14. public static final String DEAD_LETTER_QUEUE = "QD";
    15. @Bean("xExchange")
    16. public DirectExchange xExchange(){
    17. return new DirectExchange(X_EXCHANGE);
    18. }
    19. @Bean("yExchange")
    20. public DirectExchange yExchange(){
    21. return new DirectExchange(Y_DEAD_LETTER_EXCHANGE);
    22. }
    23. @Bean("queueA")
    24. public Queue queueA(){
    25. Map args = new HashMap<>();
    26. args.put("x-dead-letter-exchange",Y_DEAD_LETTER_EXCHANGE);
    27. args.put("x-dead-letter-routing-key","YD");
    28. args.put("x-message-ttl",10000);
    29. return QueueBuilder.durable(QUEUE_A).withArguments(args).build();
    30. }
    31. @Bean("queueB")
    32. public Queue queueB(){
    33. Map args = new HashMap<>(3);
    34. args.put("x-dead-letter-exchange", Y_DEAD_LETTER_EXCHANGE);
    35. args.put("x-dead-letter-routing-key", "YD");
    36. args.put("x-message-ttl", 40000);
    37. return QueueBuilder.durable(QUEUE_B).withArguments(args).build();
    38. }
    39. @Bean
    40. public Binding queueaBindingX(@Qualifier("queueA") Queue queueA,
    41. @Qualifier("xExchange") DirectExchange xExchange){
    42. return BindingBuilder.bind(queueA).to(xExchange).with("XA");
    43. }
    44. @Bean
    45. public Binding queuebBindingX(@Qualifier("queueB") Queue queue1B,
    46. @Qualifier("xExchange") DirectExchange xExchange){
    47. return BindingBuilder.bind(queue1B).to(xExchange).with("XB");
    48. }
    49. @Bean
    50. public Binding deadLetterBindingQAD(@Qualifier("queueD") Queue queueD,
    51. @Qualifier("yExchange") DirectExchange yExchange){
    52. return BindingBuilder.bind(queueD).to(yExchange).with("YD");
    53. }
    54. @Bean("queueD")
    55. public Queue queueD(){
    56. return new Queue(DEAD_LETTER_QUEUE);
    57. }
    58. }

    消息生产者代码 

    1. package com.example.demo.controller;
    2. import lombok.extern.slf4j.Slf4j;
    3. import org.springframework.amqp.rabbit.core.RabbitTemplate;
    4. import org.springframework.beans.factory.annotation.Autowired;
    5. import org.springframework.web.bind.annotation.GetMapping;
    6. import org.springframework.web.bind.annotation.PathVariable;
    7. import org.springframework.web.bind.annotation.RequestMapping;
    8. import org.springframework.web.bind.annotation.RestController;
    9. import java.util.Date;
    10. @Slf4j
    11. @RequestMapping("/ttl")
    12. @RestController
    13. public class SendMsgController {
    14. @Autowired
    15. private RabbitTemplate rabbitTemplate;
    16. @GetMapping("/sendMsg/{message}")
    17. public void sendMsg(@PathVariable String message){
    18. log.info("当前时间:{},发送一个消息给两个TTL队列:{}",new Date(),message);
    19. rabbitTemplate.convertAndSend("X","XA","消息来自ttl为10s的队列:"+message);
    20. rabbitTemplate.convertAndSend("X","XB","消息来自ttl为40s的队列:"+message);
    21. }
    22. }

    消息消费者代码

    1. package com.example.demo.consumer;
    2. import com.rabbitmq.client.Channel;
    3. import lombok.extern.slf4j.Slf4j;
    4. import org.springframework.amqp.core.Message;
    5. import org.springframework.amqp.rabbit.annotation.RabbitListener;
    6. import org.springframework.stereotype.Component;
    7. import java.io.IOException;
    8. import java.util.Date;
    9. @Slf4j
    10. @Component
    11. public class DeadLetterQueueConsumer {
    12. //接受消息
    13. @RabbitListener(queues = "QD")
    14. public void receiveD(Message message, Channel channel) throws IOException {
    15. String msg = new String(message.getBody());
    16. log.info("当前时间:{},收到死信队列信息{}", new Date().toString(), msg);
    17. }
    18. }

     发送一个请求:127.0.0.1:8080/ttl/sendMsg/haha

     第一条消息在 10S 后变成了死信消息,然后被消费者消费掉,第二条消息在 40S 之后变成了死信消息, 然后被消费掉,这样一个延时队列就打造完成了

    不过,如果这样使用的话,岂不是每增加一个新的时间需求,就要新增一个队列,这里只有 10S 和 40S 两个时间选项,如果需要一个小时后处理,那么就需要增加 TTL 为一个小时的队列,如果是预定会议室然后提前通知这样的场景,岂不是要增加无数个队列才能满足需求

    延迟队列优化

    代码架构图

    在这里新增了一个队列 QC,绑定关系如下,该队列不设置 TTL 时间

     配置文件类代码

    1. package com.example.demo.config;
    2. import org.springframework.amqp.core.*;
    3. import org.springframework.beans.factory.annotation.Qualifier;
    4. import org.springframework.context.annotation.Bean;
    5. import org.springframework.stereotype.Component;
    6. import java.util.HashMap;
    7. import java.util.Map;
    8. @Component
    9. public class MsgTtlQueueConfig {
    10. public static final String Y_DEAD_LETTER_EXCHANGE = "Y";
    11. public static final String QUEUE_C = "QC";
    12. //声明队列 C 死信交换机
    13. @Bean("queueC")
    14. public Queue queueB(){
    15. Map args = new HashMap<>(3);
    16. //声明当前队列绑定的死信交换机
    17. args.put("x-dead-letter-exchange", Y_DEAD_LETTER_EXCHANGE);
    18. //声明当前队列的死信路由 key
    19. args.put("x-dead-letter-routing-key", "YD");
    20. //没有声明 TTL 属性
    21. return QueueBuilder.durable(QUEUE_C).withArguments(args).build();
    22. }
    23. //声明队列 B 绑定 X 交换机
    24. @Bean
    25. public Binding queuecBindingX(@Qualifier("queueC") Queue queueC,
    26. @Qualifier("xExchange") DirectExchange xExchange){
    27. return BindingBuilder.bind(queueC).to(xExchange).with("XC");
    28. }
    29. }

    消息生产者代码

    1. package com.example.demo.controller;
    2. import lombok.extern.slf4j.Slf4j;
    3. import org.springframework.amqp.rabbit.core.RabbitTemplate;
    4. import org.springframework.beans.factory.annotation.Autowired;
    5. import org.springframework.web.bind.annotation.GetMapping;
    6. import org.springframework.web.bind.annotation.PathVariable;
    7. import org.springframework.web.bind.annotation.RequestMapping;
    8. import org.springframework.web.bind.annotation.RestController;
    9. import java.util.Date;
    10. @Slf4j
    11. @RequestMapping("/ttl")
    12. @RestController
    13. public class SendMsgController {
    14. @Autowired
    15. private RabbitTemplate rabbitTemplate;
    16. @GetMapping("sendExpirationMsg/{message}/{ttlTime}")
    17. public void sendMsg(@PathVariable String message,@PathVariable String ttlTime) {
    18. rabbitTemplate.convertAndSend("X", "XC", message, correlationData ->{
    19. correlationData.getMessageProperties().setExpiration(ttlTime);
    20. return correlationData;
    21. });
    22. log.info("当前时间:{},发送一条时长{}毫秒 TTL 信息给队列 C:{}", new Date(),ttlTime, message);
    23. }
    24. }

    发起请求:

    http://localhost:8080/ttl/sendExpirationMsg/你好 1/20000 http://localhost:8080/ttl/sendExpirationMsg/你好 2/2000

     看起来似乎没什么问题,但是在最开始的时候,就介绍过如果使用在消息属性上设置 TTL 的方式,消 息可能并不会按时“死亡“,因为 RabbitMQ 只会检查第一个消息是否过期,如果过期则丢到死信队列, 如果第一个消息的延时时长很长,而第二个消息的延时时长很短,第二个消息并不会优先得到执行

    Rabbitmq 插件实现延迟队列

    如果不能实现在消息粒度上的 TTL,并使其在设置的 TTL 时间 及时死亡,就无法设计成一个通用的延时队列。那如何解决呢,接下来我们就去解决该问题

    安装延时队列插件

    在官网上下载 https://www.rabbitmq.com/community-plugins.html,下载 rabbitmq_delayed_message_exchange 插件,然后解压放置到 RabbitMQ 的插件目录。或者

    链接:https://pan.baidu.com/s/1U7rdXf2yk9PRGxOJxhcY8A?pwd=d0jd 
    提取码:d0jd

     进入 RabbitMQ 的安装目录下的 plgins 目录,执行下面命令让该插件生效  rabbitmq_delayed_message_exchange

     重启RabbitMQ:systemctl restart rabbitmq-server

    然后我们就可以看管理界面

     代码架构图

    在这里新增了一个队列 delayed.queue,一个自定义交换机 delayed.exchange,绑定关系如下:

    配置文件类代码

    1. package com.example.demo.config;
    2. import org.springframework.amqp.core.Binding;
    3. import org.springframework.amqp.core.BindingBuilder;
    4. import org.springframework.amqp.core.CustomExchange;
    5. import org.springframework.amqp.core.Queue;
    6. import org.springframework.beans.factory.annotation.Qualifier;
    7. import org.springframework.context.annotation.Bean;
    8. import org.springframework.context.annotation.Configuration;
    9. import org.springframework.amqp.core.*;
    10. import java.util.HashMap;
    11. import java.util.Map;
    12. @Configuration
    13. public class DelayedQueueConfig {
    14. public static final String DELAYED_QUEUE_NAME = "delayed.queue";
    15. public static final String DELAYED_EXCHANGE_NAME = "delayed.exchange";
    16. public static final String DELAYED_ROUTING_KEY = "delayed.routingkey";
    17. @Bean
    18. public Queue delayedQueue(){
    19. return new Queue(DELAYED_QUEUE_NAME);
    20. }
    21. //自定义交换机 我们这里实现一个延迟交换机
    22. @Bean
    23. public CustomExchange delayedExchange(){
    24. Map args = new HashMap<>();
    25. //自定义交换机的类型
    26. args.put("x-delayed-type", "direct");
    27. /**
    28. * 1、交换机名称
    29. * 2、交换机类型
    30. * 3、持久化
    31. * 4、自动删除
    32. * 5、其他参数
    33. */
    34. return new CustomExchange(DELAYED_EXCHANGE_NAME, "x-delayed-message", true, false,
    35. args);
    36. }
    37. @Bean
    38. public Binding bindingDelayedQueue(@Qualifier("delayedQueue") Queue queue,
    39. @Qualifier("delayedExchange") CustomExchange
    40. delayedExchange) {
    41. return BindingBuilder.bind(queue).to(delayedExchange).with(DELAYED_ROUTING_KEY).noargs();
    42. }
    43. }

     消息生产者代码

    1. package com.example.demo.controller;
    2. import lombok.extern.slf4j.Slf4j;
    3. import org.springframework.amqp.rabbit.core.RabbitTemplate;
    4. import org.springframework.beans.factory.annotation.Autowired;
    5. import org.springframework.web.bind.annotation.GetMapping;
    6. import org.springframework.web.bind.annotation.PathVariable;
    7. import org.springframework.web.bind.annotation.RequestMapping;
    8. import org.springframework.web.bind.annotation.RestController;
    9. import java.util.Date;
    10. @Slf4j
    11. @RequestMapping("/ttl")
    12. @RestController
    13. public class SendMsgController {
    14. @Autowired
    15. private RabbitTemplate rabbitTemplate;
    16. public static final String DELAYED_EXCHANGE_NAME = "delayed.exchange";
    17. public static final String DELAYED_ROUTING_KEY = "delayed.routingkey";
    18. @GetMapping("sendDelayMsg/{message}/{delayTime}")
    19. public void sendMsg(@PathVariable String message,@PathVariable Integer delayTime) {
    20. rabbitTemplate.convertAndSend(DELAYED_EXCHANGE_NAME, DELAYED_ROUTING_KEY, message,
    21. correlationData ->{
    22. correlationData.getMessageProperties().setDelay(delayTime);
    23. return correlationData;
    24. });
    25. }
    26. }

    消息消费者代码

    1. package com.example.demo.consumer;
    2. import com.rabbitmq.client.Channel;
    3. import lombok.extern.slf4j.Slf4j;
    4. import org.springframework.amqp.core.Message;
    5. import org.springframework.amqp.rabbit.annotation.RabbitListener;
    6. import org.springframework.stereotype.Component;
    7. import java.io.IOException;
    8. import java.util.Date;
    9. @Slf4j
    10. @Component
    11. public class DeadLetterQueueConsumer {
    12. public static final String DELAYED_QUEUE_NAME = "delayed.queue";
    13. @RabbitListener(queues = DELAYED_QUEUE_NAME)
    14. public void receiveDelayedQueue(Message message){
    15. String msg = new String(message.getBody());
    16. log.info("当前时间:{},收到延时队列的消息:{}", new Date().toString(), msg);
    17. }
    18. }

    发起请求:

    http://localhost:8080/ttl/sendDelayMsg/come on baby1/20000 http://localhost:8080/ttl/sendDelayMsg/come on baby2/2000

    第二个消息被先消费掉了,符合预期

    总结 

    延时队列在需要延时处理的场景下非常有用,使用 RabbitMQ 来实现延时队列可以很好的利用 RabbitMQ 的特性,如:消息可靠发送、消息可靠投递、死信队列来保障消息至少被消费一次以及未被正 确处理的消息不会被丢弃。另外,通过 RabbitMQ 集群的特性,可以很好的解决单点故障问题,不会因为 单个节点挂掉导致延时队列不可用或者消息丢失

  • 相关阅读:
    名词作形容词的用法
    2022年第二季度全球网络攻击创新高,如何有效防范网络攻击
    【项目管理】Java使用pdfbox调用打印机打印PDF文件
    TSRFormer:复杂场景的表格结构识别新利器
    Learning Sample Relationship for Exposure Correction 论文阅读笔记
    windows驱动远程VS 2019调试
    C# 代码合集
    JDBC 连接数据库的四种方式
    【扩散模型从原理到实战】Chapter2 Hugging Face简介
    OpenAI官方吴达恩《ChatGPT Prompt Engineering 提示词工程师》(3)摘要
  • 原文地址:https://blog.csdn.net/loss_rose777/article/details/136208626