上下文持有者增强
从版本 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 值。更多信息请参见委托 Session Factory。