FTPUtils.java
2.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package com.genersoft.iot.vmp.vmanager.util;
import com.genersoft.iot.vmp.vmanager.jt1078.platform.config.FtpConfigBean;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.io.IOException;
/**
* FTP工具类
*
* @Author WangXin
* @Data 2025/2/11
* @Version 1.0.0
*/
@Log4j2
@Component
public class FTPUtils {
@Resource
private FtpConfigBean ftpConfigBean;
private FTPClient connectFtpServer() {
FTPClient ftpClient = new FTPClient();
ftpClient.setConnectTimeout(1000 * 60);
ftpClient.setControlEncoding("utf-8");
ftpClient.enterLocalPassiveMode();
int retryTimes = ftpConfigBean.getRetryTimes(); // 假设getRetryTimes方法返回int类型的重试次数,-1表示无限重试
boolean isConnected = false;
int attempts = 0;
while (!isConnected && (retryTimes == -1 || attempts < retryTimes)) {
try {
int replyCode;
ftpClient.connect(ftpConfigBean.getHost());
ftpClient.login(ftpConfigBean.getUsername(), ftpConfigBean.getPassword());
replyCode = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(replyCode)) {
log.info("连接FTP服务器 {} 失败", ftpConfigBean.getHost());
ftpClient.disconnect();
attempts++;
if (retryTimes != -1) {
log.info("第 {} 次尝试连接失败, 将重新连接", attempts);
}
continue; // 连接不成功,继续循环
}
isConnected = true;
log.info("replyCode:{}", replyCode);
} catch (IOException e) {
log.error("连接失败: {}", e.toString());
attempts++;
if (retryTimes != -1) {
log.info("第 {} 次尝试连接失败, 错误信息: {}", attempts, e.getMessage());
}
try {
// 等待一段时间再重试
Thread.sleep(ftpConfigBean.getRetryWaitTimes());
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
}
}
}
if (!isConnected) {
log.error("无法连接到FTP服务器,已达到最大重试次数");
return null;
}
return ftpClient;
}
}