【发布时间】:2020-02-07 22:02:50
【问题描述】:
我正在使用 Spring Integration 从 SFTP 服务器读取文件,并且使用带有 Java 配置的 InboundChannelAdapter 一切正常。
现在,我想修改我的流程,以便从 SFTP 服务器中删除所有已处理的文件。因此,我想使用带有 Java 配置的 SFTP OutboundGateway。这是我的新代码,基于https://docs.spring.io/spring-integration/docs/5.0.0.BUILD-SNAPSHOT/reference/html/sftp.html#sftp-outbound-gateway 进行了少量修改:
@Configuration
public class SftpConfiguration {
@Value("${sftp.host}")
String sftpHost = "";
@Value("${sftp.user}")
String sftpUser = "";
@Value("${sftp.pass}")
String sftpPass = "";
@Value("${sftp.port}")
Integer sftpPort = 0;
@Bean
public SessionFactory<LsEntry> sftpSessionFactory() {
DefaultSftpSessionFactory factory = new DefaultSftpSessionFactory(true);
factory.setHost(sftpHost);
factory.setPort(sftpPort);
factory.setUser(sftpUser);
factory.setPassword(sftpPass);
factory.setAllowUnknownKeys(true);
return new CachingSessionFactory<LsEntry>(factory);
}
@Bean
public SftpInboundFileSynchronizer sftpInboundFileSynchronizer() {
SftpInboundFileSynchronizer fileSynchronizer = new SftpInboundFileSynchronizer(sftpSessionFactory());
fileSynchronizer.setDeleteRemoteFiles(false);
fileSynchronizer.setRemoteDirectory("/upload/");
return fileSynchronizer;
}
@Bean
@InboundChannelAdapter(channel = "sftpChannel", poller = @Poller(cron = "0 * * * * ?"))
public MessageSource<File> sftpMessageSource() {
SftpInboundFileSynchronizingMessageSource source =
new SftpInboundFileSynchronizingMessageSource(sftpInboundFileSynchronizer());
source.setLocalDirectory(new File("sftp-folder"));
source.setAutoCreateLocalDirectory(true);
return source;
}
@Bean
@ServiceActivator(inputChannel = "sftpChannel")
MessageHandler handler() {
return new MessageHandler() {
@Override
public void handleMessage(Message<?> message) throws MessagingException {
File f = (File) message.getPayload();
try {
myProcessingClass.processFile(f);
SftpOutboundGateway sftpOG = new SftpOutboundGateway(sftpSessionFactory(), "rm",
"'/upload/" + f.getName() + "'");
} catch(QuoCrmException e) {
logger.error("File [ Process with errors, file won't be deleted: " + e.getMessage() + "]");
}
}
};
}
}
修改如下:
- 我将 fileSynchronizer 定义为 setDeleteRemoteFiles(false),以便根据我的流程手动删除文件。
- 在我的 MessageHandler 中,我添加了我的 SFTPOutboundGateway,如果没有异常,则表示处理成功并删除文件(但如果有异常不会删除文件)。
此代码不会删除任何文件。有什么建议吗?
【问题讨论】:
标签: java spring-integration spring-integration-sftp