基于springboot和rabbitMq实现延时重试队列

需求描述:

日常开发常见的回调通知,如果回调失败,需要重试3次,每隔半小时重试一次,超过三次则放弃回调.

实现思路:

  1. /通常普遍能想到的实现方式就是如果回调通知失败,就将该记录放到一个队列里面,然后半小时之后再去取出这一条记录进行消费.网上搜了个遍,貌似没有现成的工具包能够支持这个功能.后来了解到RabbitMq的死信队列,不熟悉的同学可以自行搜索了解死信队列的概念.简单的来说死掉的消息就会被放到这个队列.
  2. 通过了解,发现RabbitMq的消息过期和死信队列特性可以实现上述功能.消息过期比较容易了解,不熟悉死信队列的同学可以自行搜索了解概念.简单的来说死掉的消息(消息过期)可以通过被投放到死信队列,然后再由死信队列的消费者消费.其实RabbitMq里面应该是没有死信队列这个概念,只有死信交换机,人们习惯的和死信交换机有绑定关系的队列称为死信队列而已.

代码:

 

  • 生产者配置:

 

 

package com.ample16.stackdemo.config;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;

/**
 * 重试需求:回调通知,如果通知失败失败,重试3次,每10s一次,3次均失败则放弃
 * :rabbitMq的配置
 */
@Configuration
public class RetryRabbitConfig {
    //重试次数
    public static int retryCount = 3;
    //过期时间
    public static Long expiredTime = 10000L;

    /**
     * 正常的消费队列相关,包括交换机,队列,以及两者的绑定
     */
    @Bean
    public Queue NormalQueue() {
        // durable:是否持久化,默认是false,持久化队列:会被存储在磁盘上,当消息代理重启时仍然存在,暂存队列:当前连接有效
        // exclusive:默认也是false,只能被当前创建的连接使用,而且当连接关闭后队列即被删除。此参考优先级高于durable
        // autoDelete:是否自动删除,当没有生产者或者消费者使用此队列,该队列会自动删除。
        return new Queue("normalQueue", true, false, false);
    }

    @Bean
    DirectExchange NormalExchange() {
        return new DirectExchange("normalExchange", true, false);
    }

    @Bean
    Binding bindingNormalDirect() {
        //正常消费队列和交换机绑定, 并设置用于匹配键:normalRouting
        return BindingBuilder.bind(NormalQueue()).to(NormalExchange()).with("normalRouting");
    }

    /**
     * 消费失败队列相关,包括交换机,队列,以及两者的绑定
     */
    @Bean
    public Queue ProcessFailQueue() {
        //设置其的死信交换机为普通队列的交换机,消息到期后消息会死亡,然后投放到死信交换机
        String dlxName = "normalExchange";
        HashMap<String, Object> map = new HashMap<>();
        map.put("x-dead-letter-exchange", dlxName);
        map.put("x-message-ttl", expiredTime);
        //死信的路由key和正常消息的路由key一致,消息会被投放到正常队列重新消费
        map.put("x-dead-letter-routing-key", "normalRouting");
        return new Queue("processFailQueue", true, false, false, map);
    }

    @Bean
    DirectExchange ProcessFailExchange() {
        return new DirectExchange("processFailExchange", true, false);
    }

    @Bean
    Binding bindingProcessFailDirect() {
        //消费失败队列和交换机绑定, 并设置用于匹配键:normalRouting
        return BindingBuilder.bind(ProcessFailQueue()).to(ProcessFailExchange()).with("processFailRouting");
    }


}
  • 消费者的逻辑实现代码:
package com.ample16.stackdemo.config;

import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.Map;
import java.util.Random;

@Component

public class DirectReceiver {
    @Autowired
    RabbitTemplate rabbitTemplate;  //使用RabbitTemplate,这提供了接收/发送等等方法

    @RabbitHandler
    @RabbitListener(queues = "TestDeadDirectQueue")//监听的死信队列名称 TestDirectDeadQueue
    public void processDeadQueue(Map testMessage) {
        System.out.println("DirectDeadReceiver消费者收到消息  : " + testMessage.toString() + new Date());
    }

    @RabbitHandler
    @RabbitListener(queues = "normalQueue")//监听的死信队列名称 normalQueue
    public void normalQueueComsumer(Map testMessage) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//        System.out.println("normalQueue消费者收到消息  : " + testMessage.toString() + new Date());
        if (isNotifySuccess()) {
            System.out.println("normalQueue|suc|" + testMessage.toString() + "|" + LocalDateTime.now().format(formatter));
        } else {
            System.out.println("normalQueue|fail|" + testMessage.toString() + "|" + LocalDateTime.now().format(formatter));
            Integer count = (Integer) testMessage.get("count");
            if (count < 3) {
                //消费失败且未超过重试次数,重新发送到交换机processFailExchange
                testMessage.put("count", count + 1);
                rabbitTemplate.convertAndSend("processFailExchange", "processFailRouting", testMessage);
            } else {
                System.out.println("超过重复次数,放弃消息:" + testMessage.toString() + "|" + LocalDateTime.now().format(formatter));
            }
        }
    }

   /* @RabbitHandler
    @RabbitListener(queues = "processFailQueue")
    public void processFailQueueComsumer(Map testMessage) {
        System.out.println("processFailQueue消费者收到消息  : " + testMessage.toString() + new Date());
    }
*/

    /**
     * 随机模拟成功失败,偶数成功,奇数失败
     *
     * @return
     */
    public Boolean isNotifySuccess() {
        int i = new Random().nextInt(10);
        return i % 2 == 0 ? true : false;
//        return false;
    }
}

 效果图

 

 

重点:normalQueue的消息消费失败的话,手动投放到processFailQueue,processFailQueue不设置消费者,让它的消息过期死亡,然后通过死信交换机再次路由到normalQueue进行消费.normalQueue的消息来源有两个,一个是首次的正常投递,另外是processFailQueue通过死信路由器投递,这里的normalQueue也可以说是processQueue的死信队列.

 

参考文献以及代码连接:

  1. 源码:需要切换到rabbitMq分支.
  2. RabbitMq入门以及使用教程
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值