问题解决:ftp并发读取文件内容时,会出现ftp连接数过多,进而导致读取文件出现问题

场景

ftp并发读取文件内容时,过了一段时候,连接数过多,进而导致读取文件出现问题,被ftp服务器给限制了。截图如下:
在这里插入图片描述

环境

软件 版本
centos 7
jdk 8

问题原因

原来的操作代码如下:

InputStream in = null;
ByteArrayOutputStream output = null;
try {
    in = ftpClient.retrieveFileStream(ftpFilePath);
    output = new ByteArrayOutputStream();
    byte[] buffer = new byte[1024 * 4];
    int len = 0;
    while ((len = in.read(buffer)) != -1) {
        output.write(buffer, 0, len);
    }
} catch (Exception e) {
    throw e;
} finally {
    if (in != null) {
        in.close();
    }
    if (output != null) {
        output.close();
    }
}

这个是读取文件内容到程序的变量里面去,而不落地到本地文件,减少本地IO交互。程序执行完毕之后,就会关闭对应的流。但是就是这里出现了问题,没有等待ftp服务器返回响应,就直接关闭了流。官方解释,有几种FTPClient方法是没办法完成整个FTP命令序列,进而完成事务的。所以这些命令要求我们在收到肯定的中间命令后采取一些措施来保证整个事务的完成。而我们的代码完成其操作后,必须调用completePendingCommand来接收来自服务器的完成答复并验证整个事务是否成功。
在这里插入图片描述
所以,问题出现的原因是没有调用completePendingCommand来完成整个事务,导致ftp连接频繁挂掉,然后不断重新启动新的ftp连接,导致连接数过多,被ftp服务器给限制了。

解决方案

1. 官方方案

下面是官方提供的解决方法:

InputStream input;
OutputStream output;
input  = new FileInputStream("foobaz.txt");
output = ftp.storeFileStream("foobar.txt")
if(!FTPReply.isPositiveIntermediate(ftp.getReplyCode())) {
    input.close();
    output.close();
    ftp.logout();
    ftp.disconnect();
    System.err.println("File transfer failed.");
    System.exit(1);
}
Util.copyStream(input, output);
input.close();
output.close();
// Must call completePendingCommand() to finish command.
if(!ftp.completePendingCommand()) {
    ftp.logout();
    ftp.disconnect();
    System.err.println("File transfer failed.");
    System.exit(1);
}

2. 本文的解决方法

在关闭流的时候,判断是否完成,以下为解决方法代码:

InputStream in = null;
ByteArrayOutputStream output = null;
try {
    in = ftpClient.retrieveFileStream(ftpFilePath);
    output = new ByteArrayOutputStream();
    byte[] buffer = new byte[1024 * 4];
    int len = 0;
    while ((len = in.read(buffer)) != -1) {
        output.write(buffer, 0, len);
    }
} catch (Exception e) {
    throw e;
} finally {
    if (in != null) {
        in.close();
    }
    if (output != null) {
        output.close();
    }
    if (ftp != null) {
        // completePendingCommand 不能执行两次
        if (!ftp.getClient().completePendingCommand()) {
            log.warn("ftp 关闭连接,对应的ITEM信息如下:{}",itemInfo);
        }
    }
}

结果

使用命令netstat -an|grep :21来检测ftp连接数,结果如下:
在这里插入图片描述
观察程序运行结果,过了一个小时,未发现异常。问题得到解决。
在这里插入图片描述

总结

使用FTPClient的相关方法的时候,记得查看相关的文档,里面已经有比较完善的解决措施。

随缘求赞

如果我的文章对大家产生了帮忙,可以在文章底部点个赞或者收藏;
如果有好的讨论,可以留言;
如果想继续查看我以后的文章,可以左上角点击关注
在这里插入图片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章