上下文持有者建议
从版本 6.1 开始,ContextHolderRequestHandlerAdvice
已引入。
此建议从请求消息中获取一些值,并将其存储在上下文持有者中。
在目标上完成执行时,该值从上下文中是明确的MessageHandler
.
考虑这个建议的最佳方式类似于编程流程,我们将一些值存储到ThreadLocal
,从 Target 调用中访问它,然后清理ThreadLocal
执行后。
这ContextHolderRequestHandlerAdvice
需要这些构造函数参数:一个Function<Message<?>, Object>
作为价值提供者,Consumer<Object>
作为上下文集回调,将Runnable
作为上下文清理钩子。
以下是ContextHolderRequestHandlerAdvice
可与o.s.i.file.remote.session.DelegatingSessionFactory
:
@Bean
DelegatingSessionFactory<?> dsf(SessionFactory<?> one, SessionFactory<?> two) {
return new DelegatingSessionFactory<>(Map.of("one", one, "two", two), null);
}
@Bean
ContextHolderRequestHandlerAdvice contextHolderRequestHandlerAdvice(DelegatingSessionFactory<String> dsf) {
return new ContextHolderRequestHandlerAdvice(message -> message.getHeaders().get("FACTORY_KEY"),
dsf::setThreadKey, dsf::clearThreadKey);
}
@ServiceActivator(inputChannel = "in", adviceChain = "contextHolderRequestHandlerAdvice")
FtpOutboundGateway ftpOutboundGateway(DelegatingSessionFactory<?> sessionFactory) {
return new FtpOutboundGateway(sessionFactory, "ls", "payload");
}
只需向in
channel 中带有FACTORY_KEY
header 设置为one
或two
.
这ContextHolderRequestHandlerAdvice
将该标头中的值设置为DelegatingSessionFactory
通过其setThreadKey
.
然后当FtpOutboundGateway
执行ls
命令适当的委托SessionFactory
从DelegatingSessionFactory
根据其ThreadLocal
.
当从FtpOutboundGateway
一个ThreadLocal
值在DelegatingSessionFactory
根据clearThreadKey()
调用ContextHolderRequestHandlerAdvice
.
有关更多信息,请参阅委派 Session Factory。