FTPUtils.java 2.57 KB
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;
    }
}