Spring SFTP 使用以下配置进行设置。在某些环境中,它在启动时有效,但后续副本在等待 15 分钟后失败,并显示“连接超时”错误消息。
如果重新运行,副本将在“大多数情况下”再次运行。
配置
/**
* Create a SFTP session factory.
*/
@Bean
public SessionFactory<ChannelSftp.LsEntry> sftpSessionFactory() {
// TODO check isSharedSession
DefaultSftpSessionFactory factory = new DefaultSftpSessionFactory(false);
factory.setHost(host);
factory.setPort(port);
factory.setUser(user);
if (privateKey != null) {
factory.setPrivateKey(privateKey);
factory.setPrivateKeyPassphrase(keyPhrase);
} else {
factory.setPassword(password);
}
factory.setAllowUnknownKeys(allowUnknownKeys);
return new CachingSessionFactory<ChannelSftp.LsEntry>(factory);
}
使用远程文件模板,以便我们可以在远程服务器上设置名称。是的,Spring SFTP 也会重命名远程服务器上的文件。如果先重命名文件,则可以使用“网关”。
@SuppressWarnings("unchecked")
public void send(File sourceFilePath, File intermediateFileName, File destinationFileName, String remoteDirectory) throws PaymentsPlusSystemException {
SftpRemoteFileTemplate sftpRemoteFileTemplate = new SftpRemoteFileTemplate(sftpSessionFactory);
sftpRemoteFileTemplate.setAutoCreateDirectory(Boolean.TRUE);
sftpRemoteFileTemplate.setRemoteDirectoryExpression(new LiteralExpression(remoteDirectory));
sftpRemoteFileTemplate.setBeanFactory(context);
try {
sftpRemoteFileTemplate.afterPropertiesSet();
sftpRemoteFileTemplate.send(new GenericMessage<Object>(sourceFilePath));
String intermediateFileFull = remoteDirectory + "/" + intermediateFileName.getPath();
String destinationFileFull = remoteDirectory + "/" + destinationFileName.getPath();
sftpRemoteFileTemplate.rename(intermediateFileFull, destinationFileFull);
} catch (Exception e) {
throw new CopySystemException(String.format("Refund batch. Copying files. Failed to send file. %s. %s", e.getLocalizedMessage(), e.getClass().getName()), e);
}
}
最佳答案
导致问题的环境中的防火墙正在删除长时间运行的“缓存” session 。看起来它刚刚被删除,并且 SFTP 连接没有检查连接是否仍然处于 Activity 状态。
修复方法是删除缓存 session 工厂。这样做的影响是复制过程在每次操作后都会登录。例如,登录并创建目录。再次登录并复制文件。
关于Java Spring SFTP 连接无法重新连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48872108/