代码之家  ›  专栏  ›  技术社区  ›  Raja Anbazhagan

RabbitMq监听器的ServletFilter等价物是什么?

  •  1
  • Raja Anbazhagan  · 技术社区  · 7 年前

    我有一个 spring-boot 我为其实现了 MDCFilter 这增加了 UUID MDC 我可以在日志文件中找到的日志记录上下文。

    这个 Filter 类看起来像这样。

    public class MDCFilter implements Filter {
    
      @Override
      public void init(FilterConfig filterConfig) {
      }
    
      @Override
      public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
          throws IOException, ServletException {
    
        String requestId = UUID.randomUUID().toString();
    
        MDC.put(REQUEST_ID_KEY, requestId);
        response.addHeader("trace", requestId);
        try {
          chain.doFilter(req, resp);
        } finally {
          MDC.remove("trace");
        }
      }
    
      @Override
      public void destroy() {
      }
    }
    

    但最近,我们转向了通过队列处理流量,我从文档中不知道如何为消息侦听器复制这种过滤行为。

    我的听众看起来像这样。

    @RabbitListener(queues = "${queue1}")
    public void receiveMessages(Message message) {
    doTheBusinessLogic(message)
    }
    

    谁能给我指出正确的方向吗?

    1 回复  |  直到 7 年前
        1
  •  3
  •   Gary Russell    7 年前

    使用容器的 adviceChain 。假设您使用的是Boot 2.0和简单容器工厂,请重写Boot的工厂以添加建议。。。

    @SpringBootApplication
    public class So49770881Application {
    
        public static void main(String[] args) {
            SpringApplication.run(So49770881Application.class, args);
        }
    
        @Bean(name = "rabbitListenerContainerFactory")
        public SimpleRabbitListenerContainerFactory simpleRabbitListenerContainerFactory(
                SimpleRabbitListenerContainerFactoryConfigurer configurer,
                ConnectionFactory connectionFactory) {
            SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
            configurer.configure(factory, connectionFactory);
            factory.setAdviceChain(new MDCAdvice());
            return factory;
        }
    
        public static class MDCAdvice implements MethodInterceptor {
    
            @Override
            public Object invoke(MethodInvocation invocation) throws Throwable {
                // pre process
                try {
                    return invocation.proceed();
                }
                finally {
                    // post process
                }
            }
    
        }
    
    }