RabbitMq 侦听器的 ServletFilter 等价物是什么? [英] What is the ServletFilter equalent of a RabbitMq Listener?
问题描述
我有一个 spring-boot
网络应用程序,我为它实现了一个 MDCFilter
,它向 MDC
添加了一个 UUID
> 我可以在日志文件中找到的日志上下文.
I have a spring-boot
web application for which I implemented an MDCFilter
that adds a UUID
to MDC
logging context that i can find in the log file.
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() {
}
}
但最近我们转向通过队列处理流量,我从文档中没有任何线索可以为消息侦听器复制此过滤器行为.
But recently we moved towards processing traffic via Queues and I have no clue from the documents to replicate this filter behaviour for the message listeners.
我的听众看起来像这样.
My listener would look something like this.
@RabbitListener(queues = "${queue1}")
public void receiveMessages(Message message) {
doTheBusinessLogic(message)
}
谁能指出我正确的方向?
Can anyone point me to the right direction ?
推荐答案
使用容器的adviceChain
.假设您正在使用 Boot 2.0 和简单的容器工厂,请覆盖引导的工厂以添加建议...
Use the container's adviceChain
. Assuming you are using Boot 2.0 and the simple container factory, override boot's factory to add the advice...
@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
}
}
}
}
这篇关于RabbitMq 侦听器的 ServletFilter 等价物是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!