与 apache commons-vfs2 的连接过多

use*_*633 5 java apache sftp apache-commons apache-commons-vfs

我有一个应用程序需要从 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;
    }
Run Code Online (Sandbox Code Playgroud)

sim*_*005 2

VFS 的 apache commons wiki ( https://wiki.apache.org/commons/VfsFaq ) 表示在某些情况下关闭 SFTP 连接时要使用以下内容:

((DefaultFileSystemManager) fsManager).close();
Run Code Online (Sandbox Code Playgroud)

这会强制调用close上的方法,而不是类上的方法。DefaultFileSystemManagercloseFileSystemManager

这可能不是你的问题,但可能是相关的。