跳到主要内容
版本:7.0.2

Context Holder Advice

DeepSeek V3 中英对照 Context Holder Advice

从版本 6.1 开始,引入了 ContextHolderRequestHandlerAdvice。该通知从请求消息中提取某个值,并将其存储在上下文持有器中。当目标 MessageHandler 上的执行完成时,该值会从上下文中清除。理解此通知的最佳方式类似于编程流程:我们将某个值存储到 ThreadLocal 中,从目标调用中访问它,然后在执行后清理 ThreadLocalContextHolderRequestHandlerAdvice 需要以下构造函数参数:一个 Function<Message<?>, Object> 作为值提供者,一个 Consumer<Object> 作为上下文设置回调,以及一个 Runnable 作为上下文清理钩子。

以下是一个示例,展示了如何将 ContextHolderRequestHandlerAdviceo.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() 调用被清除。更多信息请参阅委托会话工厂