Spring boot FTP 连接池上传

本文介绍了如何在Spring Boot应用中使用FTP连接池进行文件批量上传,包括引入FTP相关库、配置FTP参数、创建FTPClient工厂、定义FTP连接池、实现上传下载功能以及进行测试。详细步骤涵盖从配置到实际操作的全过程。
摘要由CSDN通过智能技术生成

Spring boot FTP 连接池上传,批量上传,ftpClient 上传,支持多连接快速切换上传

 

1.引入jar

<dependency>
    <groupId>commons-net</groupId>
    <artifactId>commons-net</artifactId>
    <version>3.6</version>
</dependency>
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.6</version>
</dependency>
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-pool2</artifactId>
    <version>2.8.0</version>
</dependency>

2. FTP 配置

ftp:
  ftpServer0:
    hostname: localhost
    port: 21
    username: guest
    password: b_27Fir#MwA@Rei_nfO
    encoding: UTF-8
  ftpServer1:
     hostname: localhost
     port: 21
     username: guest
     password: b_27Fir#MwA@Rei_nfO
     encoding: UTF-8

3. 读取配置

@Component
@ConfigurationProperties(prefix = "ftp")
public class FTPProperties {

    private FtpServer ftpServer0 = new FtpServer();
    private FtpServer ftpServer1 = new FtpServer();

    @Data
    public class FtpServer {
        private String hostname;

        private Integer port;

        private String username;

        private String password;
        /**
         * 编码
         */
        private String encoding;
    }
}

 4. 添加springboot 配置,注册bean

@Configuration
@EnableConfigurationProperties(FTPProperties.class)
public class FTPConfig {
}

5. 创建 FTPClient 工厂

@Slf4j
public class FTPClientFactory extends BasePooledObjectFactory<FTPClient> {

    public FTPProperties.FtpServer ftpServer;

    public FTPClientFactory(FTPProperties.FtpServer ftpServer) {
            this.ftpServer = ftpServer;
    }

    @Override
    public FTPClient create() throws Exception {
        FTPClient ftpClient = new FTPClient();
        ftpClient.connect(ftpServer.getHostname(), ftpServer.getPort());
        if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
            ftpClient.disconnect();
            log.warn("FTP服务器拒绝连接");
            return null;
        }
        log.info("连接FTP服务器成功返回码 ==> {}", ftpClient.getReplyCode());
        ftpClient.login(ftpServer.getUsername(), ftpServer.getPassword());
        log.info("登录FTP服务器成功返回码 ==> {}", ftpClient.getReplyCode());
        ftpClient.enterLocalPassiveMode();
        return ftpClient;
    }

    /**
     * 用PooledObject封装对象放入池中
     * @param ftpClient
     * @return
     */
    @Override
    public PooledObject<FTPClient> wrap(FTPClient ftpClient) {
        return new DefaultPooledObject<>(ftpClient);
    }

    /**
     * 销毁
     * @param ftpPooled
     * @
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值