【发布时间】:2019-04-10 08:19:31
【问题描述】:
我有一个需要从 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;
}
【问题讨论】:
-
我不会初始化和关闭共享文件系统管理器。特别是不是默认的。如果您重用单个管理器,它也将重用打开的连接。还要确保您的 downloadFile() 方法实际关闭了流。
标签: java apache sftp apache-commons apache-commons-vfs