![](/img/trans.png)
[英]Moving file/files from remote directory to another Spring Integration SFTP Outbound Gateway Java Config/Java DSL
[英]Spring Integration FTP - Create dynamic directory with remote directory expression (Java config)
使用 Spring Integration 的 SFTP 會話工廠(使用 Java 配置)時,我想動態設置遠程 SFTP 服務器目錄。 Spring 文檔說這是可能的:
SpEL 和 SFTP 出站適配器
與 Spring Integration 中的許多其他組件一樣,在配置 SFTP 出站通道適配器時,您可以從 Spring 表達式語言 (SpEL) 支持中受益,方法是指定兩個屬性
remote-directory-expression
和remote-filename-generator-expression
(見上文) . 表達式評估上下文將 Message 作為其根對象,從而允許您提供表達式,這些表達式可以根據 Message 中的數據(來自payload或headers )動態計算文件名或現有目錄路徑。 在上面的示例中,我們使用表達式值定義remote-filename-generator-expression
屬性,該值根據其原始名稱計算文件名,同時附加一個后綴:- foo 。
但是我在實現這個時遇到了麻煩。 我似乎找不到使用 Spring 的 SpEL 表達式語言的好例子。 下面的代碼有效,並將我的文件發送到下面的根目錄,或者如果我在 LiteralExpression 中輸入一個特定目錄。 但我想用使用“路徑”標頭的 SpelExpression 替換 LiteralExpression 表達式,類似於我對“文件”標頭所做的動態調整正在上傳的文件名。
@Configuration
public class SftpConfig {
@Autowired
private SftpSettings sftpSettings;
@Bean
public SessionFactory<LsEntry> sftpSessionFactory() {
DefaultSftpSessionFactory factory = new DefaultSftpSessionFactory(true);
factory.setHost(sftpSettings.getHostname());
factory.setPort(sftpSettings.getPort());
factory.setUser(sftpSettings.getUsername());
factory.setPassword(sftpSettings.getPassword());
factory.setAllowUnknownKeys(true);
return new CachingSessionFactory<LsEntry>(factory);
}
@Bean
@ServiceActivator(inputChannel = "toSftpChannel")
public MessageHandler handler() {
SftpMessageHandler handler = new SftpMessageHandler(sftpSessionFactory());
handler.setAutoCreateDirectory(true); // automatically create the remote directory
handler.setRemoteDirectoryExpression(new LiteralExpression(""));
handler.setFileNameGenerator(new FileNameGenerator() {
@Override
public String generateFileName(Message<?> message) {
return (String) message.getHeaders().get("filename");
}
});
return handler;
}
@MessagingGateway
public interface UploadGateway {
@Gateway(requestChannel = "toSftpChannel")
void upload(@Payload byte[] file, @Header("filename") String filename, @Header("path") String path);
}
}
要啟動文件上傳,我執行此代碼
@Autowired
private UploadGateway gateway;
byte[] file = "test".getBytes();
path = "mydirectory";
filename = "myfilename";
gateway.upload(file, filename, path); // edited to correct parameter order error
SpEL 表達式可能非常復雜和動態。 為此,您必須聲明解析器:
ExpressionParser EXPRESSION_PARSER = new SpelExpressionParser()
並將其用於此表達式解析:
handler.setRemoteDirectoryExpression(EXPRESSION_PARSER.parseExpression("headers['path']"));
並且結果Expression
對象將針對每個請求消息進行評估。
在參考手冊中查看更多信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.