【问题标题】:Too many connections with apache commons-vfs2与 apache commons-vfs2 的连接太多
【发布时间】: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


【解决方案1】:

您可以尝试这种替代方法来清理任何临时文件并关闭所有提供程序。

FileObject src = null;

/**
 * Release system resources, close connection to the filesystem. 
 */
public void release() {
    FileSystem fs = null;

    this.src.close(); // Seems to still work even if this line is omitted
    fs = this.src.getFileSystem(); // This works even after the src is closed.
    this.fsManager.closeFileSystem(fs);
}

更多详情请访问:https://cwiki.apache.org/confluence/display/COMMONS/SimpleSftpFileDownload

【讨论】:

    【解决方案2】:

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

    ((DefaultFileSystemManager) fsManager).close();
    

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-08-30
      • 2013-11-21
      • 2017-12-23
      • 2018-10-19
      • 2020-04-09
      • 2019-12-02
      • 2018-04-04
      相关资源
      最近更新 更多