如需使用最新稳定版本,请使用 Spring Integration 7.0.4spring-doc.cadn.net.cn

上下文持有者建议

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

以下是 ContextHolderRequestHandlerAdvice 如何与 o.s.i.file.remote.session.DelegatingSessionFactory 结合使用的示例:spring-doc.cadn.net.cn

@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 头设置为 onetwoContextHolderRequestHandlerAdvice 会通过其 setThreadKey 将该头的值设置到 DelegatingSessionFactory 中。 随后,当 FtpOutboundGateway 执行 ls 命令时,会根据其 ThreadLocal 中的值从 DelegatingSessionFactory 中选择合适的委托 SessionFactory。 当从 FtpOutboundGateway 生成结果后,将根据来自 ContextHolderRequestHandlerAdviceclearThreadKey() 调用,清除 DelegatingSessionFactory 中的 ThreadLocal 值。 有关更多信息,请参阅 委托会话工厂spring-doc.cadn.net.cn