我有一个应用程序需要从 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();
这会强制调用 DefaultFileSystemManager
上的 close
方法,而不是 FileSystemManager
上的 close
方法> 类。
这可能不是您的问题,但可能是相关的。
关于java - 与 apache commons-vfs2 的连接过多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53180385/