上下文持有者增強

從版本 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 產生結果後,ContextHolderRequestHandlerAdvice 會根據 clearThreadKey() 呼叫清除 DelegatingSessionFactory 中的 ThreadLocal 值。更多資訊請參見委託 Session Factory