在spring集成中使用poller for service activator,如何在线程池中传递MCD(slf4j)


<service-activator ref="serviceName" input-channel="request-channel" method="methodName">
<poller task-executor="taskExecutorCustom"/>
</service-activator>
<task:executor id="taskExecutorCustom" pool-size="5-20" queue-capacity="0"> 

有人能建议我如何将MCD上下文传递给服务方法"serviceName"吗?

答案是对将在该TaskExecutor上执行的Runnable进行去马赛克

互联网上有很多关于此事的文章:

如何将MDC与线程池一起使用?

https://gist.github.com/pismy/117a0017bf8459772771

https://rmannibucau.metawerx.net/post/javaee-concurrency-utilities-mdc-propagation

此外,Spring Security还提供了一些如何将SecurityContext从一个线程传播到另一个线程的解决方案:https://docs.spring.io/spring-security/site/docs/5.3.0.RELEASE/reference/html5/#concurrency

我建议您从这些链接中获得一些想法,并在ThreadPoolTaskExecutor:中使用现有的API

/**
* Specify a custom {@link TaskDecorator} to be applied to any {@link Runnable}
* about to be executed.
* <p>Note that such a decorator is not necessarily being applied to the
* user-supplied {@code Runnable}/{@code Callable} but rather to the actual
* execution callback (which may be a wrapper around the user-supplied task).
* <p>The primary use case is to set some execution context around the task's
* invocation, or to provide some monitoring/statistics for task execution.
* @since 4.3
*/
public void setTaskDecorator(TaskDecorator taskDecorator) {

所以,你的装饰器应该有一个这样的代码:

taskExecutor.setTaskDecorator(runnable -> {
Map<String, String> mdc = MDC.getCopyOfContextMap();
return () -> {
MDC.setContextMap(mdc);
runnable.run();
};
});

最新更新