RabbitMq延迟、重试队列及Spring Boot的黑科技

背景

Spring Boot对于Rabbit有了AutoConfig的功能,但是延迟队列及失败重试却没有很好的实现

  • 延迟队列
    延迟队列存储的对象肯定是对应的延时消息,所谓”延时消息”是指当消息被发送以后,并不想让消费者立即拿到消息,而是等待指定时间后,消费者才拿到这个消息进行消费。
  • 失败自动重试
    对于有些消息,有可能种种原因业务方消费失败,而又想重新让该消息自动进行重试的功能,实现类似RocketMq重试队列的功能

实现原理

  • 延迟队列可以基于RabbitMq的DeadLetterExchange来实现,而DeadLetterExchange顾名思义,就是死信邮箱,类似于RocketMq的死信队列的味道存在,将消息发送到死信邮箱,通过设置以下三个参数来讲消息重新路由到真正的队列上
     x-message-ttl:  1000    //消息延迟时间
     x-dead-letter-exchange: tradeExchange   //失败后重新将消息路由到具体exchange上
     x-dead-letter-routing-key:  tradeRouteKey   //失败后重新将消息路由到具体routeKey上
    

具体原理可以参考 <a href="http://blog.csdn.net/u014308482/article/details/53036770">延迟队列原理</a>

  • 失败自动重试有两种做法
    1)原生的spring rabbit是基于spring retry机制来做,重复调用invokeListener来实现失败重试的功能
    2)还是基于DeadLetterExchange来做失败重试的功能
    两者的优缺点有:
  • spring-retry来说优点是spring rabbit已经帮忙实现好了,配置即可使用,但是存在一个问题,使用该方式会导致消费线程堵塞,以及如果在失败重试的过程中宕机了,该重试将彻底不起作用
  • 基于DeadLetterExchange的话,没有实现,需要自己写代码实现,不会产生消费线程堵塞的问题,消息不会肯定不会丢失

如何基于spring boot来实现

基于上面两者需求,在spring boot下如何实现呢?

spring boot rabbit的自动化配置的问题
@Configuration
@ConditionalOnClass({ RabbitTemplate.class, Channel.class })
@EnableConfigurationProperties(RabbitProperties.class)
@Import(RabbitAnnotationDrivenConfiguration.class)
public class RabbitAutoConfiguration {

RabbitAnnotationDrivenConfiguration这个Configuration

  • 作用是消费监听的主要自动化配置,构建SimpleRabbitListenerContainer,而我们要实现失败重试的功能的话,必须要有一个将消息重新发送到死信邮箱的功能

  • RabbitAnnotationDrivenConfiguration是在RabbitAutoConfiguration之前加载,在构建的时候RabbitTemplate还没开始初始化,所以RabbitAnnotationDrivenConfiguration这种方式是无法注入RabbitTemplate的

总结:基于这种情况Spring boot的rabbit 的自动化配置我们只能自己重新定义,而需要将原生的spring boot rabbit的自动化配置给屏蔽掉

如何屏蔽spring boot的自动化配置

大家可以看看这篇文章 <a href="http://www.jianshu.com/p/aa27507df448">Spring Boot自动化配置的利弊及解决之道</a>
但是这种做法对于两个框架层面上存在问题

  • 无法保证用户去配置@EnableAutoConfiguration(exclude={RabbitAutoConfiguration.class})
  • 担心是否会覆盖用户配置的spring.autoconfigure.exclude的值

总结就是:期望就是引入jar就能自动给我解决这些问题,我不想多加任何配置

spring boot的黑科技

我们看看spring将autoconfig给exclude的源码,看看这个类AutoConfigurationImportSelector

private List<String> getExcludeAutoConfigurationsProperty() {
        if (getEnvironment() instanceof ConfigurableEnvironment) {
            RelaxedPropertyResolver resolver = new RelaxedPropertyResolver(
                    this.environment, "spring.autoconfigure.");
            Map<String, Object> properties = resolver.getSubProperties("exclude");
            if (properties.isEmpty()) {
                return Collections.emptyList();
            }
            List<String> excludes = new ArrayList<String>();
            for (Map.Entry<String, Object> entry : properties.entrySet()) {
                String name = entry.getKey();
                Object value = entry.getValue();
                if (name.isEmpty() || name.startsWith("[") && value != null) {  //黑科技出现
                    excludes.addAll(new HashSet<String>(Arrays.asList(StringUtils
                            .tokenizeToStringArray(String.valueOf(value), ","))));
                }
            }
            return excludes;
        }
        RelaxedPropertyResolver resolver = new RelaxedPropertyResolver(getEnvironment(),
                "spring.autoconfigure.");
        String[] exclude = resolver.getProperty("exclude", String[].class);
        return (Arrays.asList(exclude == null ? new String[0] : exclude));
    }

这里吐槽一下,spring boot的这个代码写的真心不咋样,黑科技一下子就能体现出来了,我们发现spring boot对于Property是基于两层方式的,如果是基于PropertiesPropertySource的name含有[的话,他就会累加,而不是覆盖,所以最终我们可以在代码中这样实现屏蔽自动化配置

public class RabbitEnviromentPostProcessor implements EnvironmentPostProcessor, Ordered {
  private static final String EXCLUDE_AUTOCONFIGURATION =
      "spring.autoconfigure.exclude[rabbitSource]"; //这里一定要加[,否则将会用户在Application.yml的配置给覆盖掉了

  private static final String RABBIT_AUTOCONFIGURATION =
      "org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration";

  @Override
  public void postProcessEnvironment(ConfigurableEnvironment environment,
      SpringApplication application) {

    try {
      MutablePropertySources mutablePropertySources = environment.getPropertySources();
      Properties propertySource = new Properties();
      propertySource.setProperty(EXCLUDE_AUTOCONFIGURATION, RABBIT_AUTOCONFIGURATION);
      EnumerablePropertySource<?> enumerablePropertySource =
          new PropertiesPropertySource("rabbitSource", propertySource);
      mutablePropertySources.addFirst(enumerablePropertySource);
    } catch (Exception e) {
      log.error(e.getMessage(), e);
    }


  }

  @Override
  public int getOrder() {
    return 0;
  }
}

最终的话,我们在spring.factories上配置上这个EnvironmentPostProcessor就可以了

org.springframework.boot.env.EnvironmentPostProcessor=com.dianrong.platform.amqp.RabbitEnviromentPostProcessor

基于这种方式,好处是在代码中实现了将spring boot的autoconfig功能给屏蔽掉,不会增加配置工作量

延迟队列和重试队列的具体实现

以上聊了这么多就是为了实现延迟队列及重试队列的功能做的铺垫

  • 延迟队列实现
    拦截所有的调用发送消息的方法,如果开启了延迟队列的功能,将他的Exchange自动改为DeadLetterExchange,如:

在发送端的方法体上加上 @Delay的注解

  @Delay
  public void send() {
    this.rabbitTemplate.convertAndSend("testexchange", "testroute", "hello");
  }

扩展RabbitTemplate

@Override
  protected void doSend(Channel channel, String exchange, String routingKey, Message message,
      boolean mandatory, CorrelationData correlationData) throws Exception {
    try {
      String exchangeCopy = exchange;
      if (DELAY_QUEUE_CONTENT.get()) { //如果当前线程上下文开启了延迟队列,将自动exchange改为RabbitTemplate
        exchangeCopy = "DeadLetterExchange";
      }
      super.doSend(channel, exchangeCopy, routingKey, message, mandatory, correlationData);
    } finally {
      setDelayQueue(Boolean.FALSE);
    }

  }
  • 重试队列的实现
    扩展MessageRecoverer的恢复,如果是消费失败了,重新发送到DeadLetterExchange上
@Override
  public void recover(Message message, Throwable cause) {
    MessageProperties messageProperties = message.getMessageProperties();
    Map<String, Object> headers = message.getMessageProperties().getHeaders();
    Integer republishTimes = (Integer) headers.get(X_REPUBLISH_TIMES);
    if (republishTimes != null) { //如果超过了重试次数,直接返回
      if (republishTimes >= recoverTimes) {
        log.warn(String.format("this message [ %s] republish times >= %d times, and will discard",
            message.toString(), RabbitConstant.DEFAULT_REPUBLISH_TIMES));
        return;
      } else {
        republishTimes = republishTimes + 1; //重试次数+1
      }
    } else {
      republishTimes = 1;
    }
    headers.put(RepublishDeadLetterRecoverer.X_REPUBLISH_TIMES, republishTimes);
    messageProperties.setRedelivered(true);
    headers.put(X_EXCEPTION_STACKTRACE, getStackTraceAsString(cause));
    headers.put(X_EXCEPTION_MESSAGE,
        cause.getCause() != null ? cause.getCause().getMessage() : cause.getMessage());
    headers.put(X_ORIGINAL_EXCHANGE, message.getMessageProperties().getReceivedExchange());
    headers.put(X_ORIGINAL_ROUTING_KEY, message.getMessageProperties().getReceivedRoutingKey());
    String routingKey = genRouteKey(message);
    this.errorTemplate.send("DeadLetterExchange", routingKey, message);
    log.info("The #" + republishTimes + " republish message ["
        + message.getMessageProperties().getMessageId() + "] to exchange [" + this.errorExchangeName
        + "] and routingKey[" + routingKey + "]");
  }

以上就是如何在spring boot的框架下如何比较优雅的实现延迟及重试队列的一些做法,具体代码的话,改天上传到Github上,也欢迎关注我的 <a href="https://github.com/linking12/">GitHub</a>

实现源码 https://github.com/linking12/spring-boot-starter-rabbit

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 157,012评论 4 359
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 66,589评论 1 290
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 106,819评论 0 237
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,652评论 0 202
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 51,954评论 3 285
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,381评论 1 210
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,687评论 2 310
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,404评论 0 194
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,082评论 1 238
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,355评论 2 241
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,880评论 1 255
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,249评论 2 250
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,864评论 3 232
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,007评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,760评论 0 192
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,394评论 2 269
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,281评论 2 259

推荐阅读更多精彩内容