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 >延遲隊列原理</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.lxweimin.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 >GitHub</a>

實現源碼 https://github.com/linking12/spring-boot-starter-rabbit

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容