在弹簧集成中使用轮询器作为服务激活器,如何在线程池中传递MCD(slf4j)上下文

问题描述 投票:0回答:1
 <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”的方法?

spring-integration slf4j
1个回答
0
投票

答案是decorace一个要在该Runnable上执行的TaskExecutor

[Internet上有很多关于此事的文章:

How to use MDC with thread pools?

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();
        };
    });
© www.soinside.com 2019 - 2024. All rights reserved.