上下文持有者建议
从 6.1 版本开始,引入了 ContextHolderRequestHandlerAdvice
。此建议从请求消息中获取某些值并将其存储在上下文持有者中。当在目标 MessageHandler
上完成执行时,该值会从上下文中清除。理解这个建议的最佳方式是类似于编程流程,我们将某些值存储到 ThreadLocal
中,在目标调用中访问它,然后在执行后清理 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
通道发送一条消息,并将 FACTORY_KEY
头设置为 one
或 two
。ContextHolderRequestHandlerAdvice
通过其 setThreadKey
方法将该头的值设置到 DelegatingSessionFactory
中。然后当 FtpOutboundGateway
执行 ls
命令时,会根据 DelegatingSessionFactory
中的 ThreadLocal
的值选择合适的 SessionFactory
。当从 FtpOutboundGateway
产生结果时,根据来自 ContextHolderRequestHandlerAdvice
的 clearThreadKey()
调用清除 DelegatingSessionFactory
中的 ThreadLocal
值。更多详情请参见 委托会话工厂。