问题解决:ftp并发读取文件内容时,会出现ftp连接数过多,进而导致读取文件出现问题 | 您所在的位置:网站首页 › 卡夜阁怎么看不到了 › 问题解决:ftp并发读取文件内容时,会出现ftp连接数过多,进而导致读取文件出现问题 |
文章目录
场景环境问题原因解决方案1. 官方方案2. 本文的解决方法
结果总结随缘求赞
场景
ftp并发读取文件内容时,过了一段时候,连接数过多,进而导致读取文件出现问题,被ftp服务器给限制了。截图如下: 原来的操作代码如下: 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来接收来自服务器的完成答复并验证整个事务是否成功。 下面是官方提供的解决方法: 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的相关方法的时候,记得查看相关的文档,里面已经有比较完善的解决措施。 随缘求赞如果我的文章对大家产生了帮忙,可以在文章底部点个赞或者收藏; 如果有好的讨论,可以留言; 如果想继续查看我以后的文章,可以左上角点击关注 |
CopyRight 2018-2019 实验室设备网 版权所有 |