记录一次java使用ftp报错
在使用java连接ftp服务器中出现的问题-FTP response 421 received. Server closed connection
@XxlJob("handleMeiTuanFile")
@Override
public void handleMeiTuanFile() throws IOException {
long begin = System.currentTimeMillis();
XxlJobHelper.log("解析开始");
String server = "192.168.10.128";
int port = 21;
String user = "root";
String password = "123456";
String remoteFilePath = "/tup";
String sourceDir = "/tup";
String targetDir = "/tup/bak";
FTPClient ftpClient = new FTPClient();
try {
if(!ftpClient.isConnected()){
ftpClient.connect(server, port);
ftpClient.login(user, password);
}
ftpClient.setControlEncoding("UTF-8");//中文支持
//ftpClient.enterLocalPassiveMode(); // 设置为被动模式
ftpClient.enterLocalActiveMode();
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
FTPFile[] files = ftpClient.listFiles(remoteFilePath);
String accountperiod = jdCollectionPlanRecordMapper.getAccountperiod();
for (FTPFile file : files) {
String fileName = file.getName();
String sourceFilePath = remoteFilePath + "/" + fileName;
String targetFilePath = targetDir + "/" + fileName;
if (file.isFile()) {
XxlJobHelper.log("开始获取文件");
// 下载远程文件到本地
File downloadPath = File.createTempFile("meituanTempFile_", ".xlsx");
try (FileOutputStream fos = new FileOutputStream(downloadPath)) {
boolean success = ftpClient.retrieveFile(sourceFilePath, fos);
if (success) {
XxlJobHelper.log("开始解析文件");
// 导入在线文档
EasyExcel.read(downloadPath, ExcelMeituanSettlement.class,
new ExcelMeituanSettlementListener(jdFileImportService, fileName, null,
"FTP导入", accountperiod)).sheet().doRead();
if (null != downloadPath) {
// 删除临时文件
downloadPath.deleteOnExit();
}
System.out.println("File downloaded successfully.");
ftpClient.rename(sourceFilePath, targetFilePath);
} else {
System.out.println("Failed to download file.");
}
}
}
}
for (FTPFile file : files) {
String fileName = file.getName();
String filePath = sourceDir + "/" + fileName;
if (file.isFile()) {
ftpClient.deleteFile(filePath);
}
}
long end = System.currentTimeMillis();
long cost = (end - begin)/1000;
feishuMessageService.sendMsgByKp(null, FeishuTemplateTypeEnum.meituanFtp, null,"文件结束,耗时:"+cost,0);
XxlJobHelper.log("解析结束");
System.out.println("Files migrated successfully.");
} catch (Exception e) {
e.printStackTrace();
}finally {
System.out.println("关闭");
ftpClient.logout();
ftpClient.disconnect();
}
}
开始是怀疑是连接数达到了上限
查阅资料后发现
1.Connection closed without indication.//FTP服务器服务有故障,或是是网络问题。
2. FTP response 421 received. Server closed connection.//错误原因就是FTP服务器端连接数满了
描述
本地可以正常使用正常的上传下载都没问题,拿同事的电脑测试也是正常的,发布到测试环境(K8s环境)服务跑起来就报错
在报错之前(之前测试环境用很正常),ftp服务可以正常获取连接,可以正常的上传下载文件,当环境连接ftp服务一段时间后,就会报错FTP response 421 received. Server closed connection,最开始时,怀疑过是,在创建ftp连接后没有关闭,重构了一次ftp工具类,将所有开启连接的地方都加上了关闭操作,还是报相同错误;经过百度后,查询出需要再代码中添加如下设置:
//设置被动模式
ftpClient.enterLocalPassiveMode();
在添加完后,再没有出现之前的错误了。怀疑是网络做了什么限制,由于没有权限去查看,临时处理