RabbitMQ-延时队列

实现延时队列逻辑

RabbitMQ是没有直接实现延时队列的,可以使用死信队列或者是插件的形式实现延时队列。

本次质演示使用死信队列实现延时队列。

思想:生产者正常往RabbitMQ的正常队列中发送消息。不过这里给队列设置了TTL(消息在此队列的存活时间)。超过TTL后,消息则会进入死信队列。然后由监听死信队列的消费者消费此条消息。以此实现消息的延时。

RabbitMQConfig

队列以及交换机的配置文件

java 复制代码
    //正常队列,消息只存在10秒,如果没有人消费,则进入死信队列,做延时消费
    @Bean("normalQueue")
    public Queue normalQueue() {
        return QueueBuilder.durable(Constants.NORMAL_QUEUE).ttl(10000).deadLetterExchange(Constants.DL_EXCHANGE).deadLetterRoutingKey("dl").build();
    }

    //正常消息的交换机
    @Bean("normalExchange")
    public DirectExchange normalExchange() {
        return ExchangeBuilder.directExchange(Constants.NORMAL_EXCHANGE).build();
    }

    //绑定关系
    @Bean("normalBinding")
    public Binding normalBinding(@Qualifier("normalQueue") Queue queue, @Qualifier("normalExchange") DirectExchange exchange) {
        return BindingBuilder.bind(queue).to(exchange).with("normal");
    }

    //死信队列
    @Bean("dlQueue")
    public Queue dlQueue() {
        return QueueBuilder.durable(Constants.DL_QUEUE).build();
    }

    //死信交换机
    @Bean("dlExchange")
    public DirectExchange dlExchange() {
        return ExchangeBuilder.directExchange(Constants.DL_EXCHANGE).build();
    }

    //死信绑定关系
    @Bean("dlBinding")
    public Binding dlBinding(@Qualifier("dlQueue") Queue queue, @Qualifier("dlExchange") DirectExchange exchange) {
        return BindingBuilder.bind(queue).to(exchange).with("dl");
    }
生产者
java 复制代码
    public String sendMessage() {
        for (int i = 0; i < 10; i++) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
	        rabbitTemplate.convertAndSend(Constants.NORMAL_EXCHANGE,"normal","hello direct " + i);
	        System.out.printf("%tc 消息发送成功 \n",new Date());
        }
        return "test fanout success...";
    }
消费者消费消息

这里只消费死信队列即可,正常的队列不消费,直接等待消息过期,进入死信队列

java 复制代码
    @RabbitListener(queues = "dl")
    public void messageHandler(Message message) throws UnsupportedEncodingException {
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        System.out.printf("[delay.queue] %tc 接收到消息: %s, deliveryTag: %d \n",new Date(),new String(message.getBody(),"UTF-8"),deliveryTag);

        //业务处理
    }
相关推荐
bug菌1 小时前
CAP定理真的是死结?业务系统到底该怎么取舍!
分布式·后端·架构
春马与夏7 小时前
Spark on yarn的作业提交流程
大数据·分布式·spark
XiaoQiong.Zhang7 小时前
Spark 性能调优七步法
大数据·分布式·spark
yuren_xia10 小时前
RabbitMQ核心函数的参数意义和使用场景
分布式·rabbitmq
jstart千语1 天前
【Redisson】锁可重入原理
redis·分布式·redisson
暗离子跃迁1 天前
达梦数据库单机部署dmhs同步复制(dm8->kafka)
linux·运维·数据库·分布式·学习·kafka·达梦数据库
代码的知行者1 天前
分布式数据库中间件-Sharding-JDBC
数据库·分布式·中间件
啾啾Fun1 天前
Java面试题:分布式ID时钟回拨怎么处理?序列号耗尽了怎么办?
java·分布式·分布式id·八股
jarenyVO1 天前
RabbitMQ全面学习指南
数据库·学习·rabbitmq