我有一个需要从sftp下载文件的应用程序。
我目前正在使用apache commons-vfs2
我有一个调度程序,每1分钟运行一次。
1.获取远程文件列表(打开连接,获取列表,然后关闭连接)
2.从步骤1下载文件(打开连接,下载每个文件,然后关闭连接)
如何保持最小连接?
有没有办法限制我与commons-vfs2的连接数量?
这是我的代码
private List<FileObject> getRemoteFilesList() throws FileSystemException {
FileObject[] remoteFiles;
try {
manager.init();
final @Cleanup FileObject remoteDirectoryObject = manager.resolveFile(uri, fileSystemOptions);
remoteFiles = remoteDirectoryObject.getChildren();
} finally {
manager.freeUnusedResources();
manager.close();
}
return Arrays.stream(remoteFiles)
.collect(Collectors.toList());
}
private List<File> downloadRemoteFiles(final List<FileObject> remoteFiles) {
if(remoteFiles.isEmpty()) {
return Collections.emptyList();
}
final List<File> myCollection = new ArrayList<>();
try {
manager.init();
for (final FileObject myfile : remoteFiles) {
final File localFile = downloadFile(myfile);
myCollection.add(localFile);
myfile.delete();
}
} catch (final IOException exception) {
log.warn("Unable to download because ", exception);
} finally {
manager.freeUnusedResources();
manager.close();
}
return myCollection;
}
最佳答案
VFS的apache commons Wiki(https://wiki.apache.org/commons/VfsFaq)表示在某些情况下关闭SFTP连接时使用以下内容:
((DefaultFileSystemManager) fsManager).close();
这将强制调用
close
上的DefaultFileSystemManager
方法,而不是close
类上的FileSystemManager
方法。这可能不是您的问题,但这可能是相关的。