上下文持有者通知

从 6.1 版本开始,引入了 ContextHolderRequestHandlerAdvice。 此通知从请求消息中获取一些值,并将其存储在上下文持有者中。 当目标 MessageHandler 上的执行完成后,该值会从上下文中清除。 理解此通知的最佳方式类似于编程流程,即我们将一些值存储到 ThreadLocal 中,从目标调用中访问它,然后在执行后清理 ThreadLocalContextHolderRequestHandlerAdvice 需要以下构造函数参数:一个 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 头设置为 onetwo 即可。 ContextHolderRequestHandlerAdvice 通过其 setThreadKey 将该头中的值设置到 DelegatingSessionFactory 中。 然后,当 FtpOutboundGateway 执行 ls 命令时,DelegatingSessionFactory 会根据其 ThreadLocal 中的值选择适当的委托 SessionFactory。 当 FtpOutboundGateway 产生结果时,DelegatingSessionFactory 中的 ThreadLocal 值会根据 ContextHolderRequestHandlerAdviceclearThreadKey() 调用而被清除。 更多信息请参阅 Delegating Session Factory