ftp连接池实现文件上传下载

1、pom中引入依赖

<!-- FTp上传依赖-->
        <dependency>
            <groupId>commons-net</groupId>
            <artifactId>commons-net</artifactId>
            <version>3.6</version>
        </dependency>
        <!-- 使用commons-pool 实现FTP连接池 -->
        <dependency>
            <groupId>commons-pool</groupId>
            <artifactId>commons-pool</artifactId>
            <version>1.6</version>
        </dependency>

2、设置ftp连接信息

在yml文件中设置

## ftp 服务器配置
FTP:
    ## 配置 ftp 服务器的 ip
    HOSTNAME: 10.10.1.xxx
    ## ftp 服务的端口号
    PORT: 21
    ## 用于登录 ftp 服务器的用户
    USERNAME: ftpweb
    ## 用户的密码
    PASSWORD: aaaa
    ## ftp连接池的连接对象个数
    DEFAULTPOOLSIZE: 15
    ## 用户上传的文件的保存地址
    ## ftp 服务器配置时、指定了 ftp上传的 起始目录
    ## 完整地址: ftp起始目录/resource/ghtz/
    FILEPATH: /resource/ghtz/

编写实体类获取ftp连接信息,其中获取yml文件的信息使用@Value("${path}")的形式

package com.hwhy.hainandatacheck.common.util.ftp;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * 文件上传常量
 * @className FtpConstant
 * @description TODO
 * @date 2020/6/24-17:21
 */
@Component
public class FtpConstant {

    /**
     * 规定文件名编码
     */
    private static String serverCharset = "ISO-8859-1";

    /**
     * 本地字符编码
     */
    private static String localCharset = "UTF-8";

    /**
     * 服务器地址
     */
    private static String hostName;

    /**
     * 服务器端口号默认为
     */
    private static Integer port;

    /**
     * 登录账号
     */
    private static String username;

    /**
     * 登录密码
     */
    private static String password;

    /**
     * 文件保存路径
     */
    private static String filePath;

    /**
     *
     */
    private static Integer defultPoolSize;

    public void setServerCharset(String serverCharset) {
        FtpConstant.serverCharset = serverCharset;
    }

    public void setLocalCharset(String localCharset) {
        FtpConstant.localCharset = localCharset;
    }

    @Value("${FTP.HOSTNAME}")
    public void setHostName(String hostName) {
        FtpConstant.hostName = hostName;
    }

    @Value("${FTP.PORT}")
    public void setPort(Integer port) {
        FtpConstant.port = port;
    }

    @Value("${FTP.USERNAME}")
    public void setUsername(String username) {
        FtpConstant.username = username;
    }

    @Value("${FTP.PASSWORD}")
    public void setPassword(String password) {
        FtpConstant.password = password;
    }

    @Value("${FTP.FILEPATH}")
    public void setFilePath(String filePath) {
        FtpConstant.filePath = filePath;
    }

    @Value("${FTP.DEFAULTPOOLSIZE}")
    public void setDefultPoolSize(Integer defultPoolSize) {
        FtpConstant.defultPoolSize = defultPoolSize;
    }

    public String getServerCharset() {
        return serverCharset;
    }

    public String getLocalCharset() {
        return localCharset;
    }

    public String getHostName() {
        return hostName;
    }

    public Integer getPort() {
        return port;
    }

    public String getUsername() {
        return username;
    }

    public String getPassword() {
        return password;
    }

    public String getFilePath() {
        return filePath;
    }

    public Integer getDefultPoolSize() {
        return defultPoolSize;
    }
}

3、编写ftp工厂

主要作用是生产ftp连接对象,实现 PoolableObjectFactory 接口后重写接口的几个方法,这个写法比较固定

package com.hwhy.hainandatacheck.common.util.ftp;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.commons.pool.PoolableObjectFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@Slf4j
@SuppressWarnings("all")
public class FtpFactory implements PoolableObjectFactory<FTPClient> {

    /**
     * 生成ftp连接对象
     *
     * @return
     * @throws Exception
     */
    @Override
    public FTPClient makeObject() throws Exception {
        FTPClient ftpClient = new FTPClient();
        ftpClient.setControlEncoding("utf-8");
        try {
            FtpConstant ftpConstant = new FtpConstant();
            log.info("连接ftp服务器:" + ftpConstant.getHostName() + ":" + ftpConstant.getPort());
            //连接ftp服务器
            if (!ftpClient.isConnected()) {
                ftpClient.connect(ftpConstant.getHostName(), ftpConstant.getPort());
            }
            //登录ftp服务器
            ftpClient.login(ftpConstant.getUsername(), ftpConstant.getPassword());
            //是否成功登录服务器
            int replyCode = ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(replyCode)) {
                log.info("连接失败ftp服务器:" + ftpConstant.getHostName() + ":" + ftpConstant.getPort());
            }
            //连接超时为60秒
            ftpClient.setConnectTimeout(60000);
            log.info("FTP服务器 >>>>>>> 连接成功");
            FTPReply.isPositiveCompletion(ftpClient.sendCommand("OPTS UTF8", "ON"));
            ftpClient.setControlEncoding(ftpConstant.getLocalCharset());
            return ftpClient;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ftpClient;
    }

    /**
     * 释放ftp连接资源
     *
     * @param ftpClient
     * @throws Exception
     */
    @Override
    public void destroyObject(FTPClient ftpClient) throws Exception {
        try {
            if(ftpClient != null && ftpClient.isConnected()) {
                ftpClient.logout();
            }
        } catch (Exception e) {
            log.error("ftp Exception , 错误信息:", e);
            throw e;
        } finally {
            if(ftpClient != null) {
                ftpClient.disconnect();
            }
        }
    }

    /**
     * 验证 ftp连接对象 的有效性
     *
     * @param ftpClient
     * @return
     */
    @Override
    public boolean validateObject(FTPClient ftpClient) {
        try {
            return ftpClient.sendNoOp();
        } catch (Exception e) {
            log.error("Failed to validate client: {}");
        }
        return false;
    }

    @Override
    public void activateObject(FTPClient ftpClient) throws Exception {

    }

    @Override
    public void passivateObject(FTPClient ftpClient) throws Exception {

    }
}

4、编写ftp连接池

使用ftp工厂生产ftp连接对象并存入ftp连接池中,实现implements ObjectPool 接口后也是重写接口的几个方法,写法也比较固定

package com.hwhy.hainandatacheck.common.util.ftp;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.pool.ObjectPool;
import org.apache.commons.pool.PoolableObjectFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.NoSuchElementException;
import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;

@Slf4j
public class FtpPool implements ObjectPool<FTPClient> {

    public static FtpFactory ftpFactory = new FtpFactory();

    public static BlockingQueue<FTPClient> blockingQueue;

    public static FtpConstant ftpConstant = new FtpConstant();


    /**
     * 初始化ftp连接池
     *
     * @param maxPoolSize
     * @throws Exception
     */
    static  {
        blockingQueue = new ArrayBlockingQueue<FTPClient>(ftpConstant.getDefultPoolSize());
        FtpFactory factory = new FtpFactory();

        int count = 0;
        while (count < ftpConstant.getDefultPoolSize()) {
            try {
                blockingQueue.offer(factory.makeObject());
                //blockingQueue.offer(factory.makeObject(), 20000, TimeUnit.MINUTES);
            }catch (Exception e){
                log.error("初始化ftpPool 时 FtpFactory的makeObject()错误:" , e);
            }
            count++;
        }
        log.info("ftpPool中连接对象个数为:"+blockingQueue.size());
    }


    /**
     * 从 ftpPool 中获取连接对象
     *
     * @return
     * @throws Exception
     * @throws NoSuchElementException
     * @throws IllegalStateException
     */
    @Override
    public FTPClient borrowObject() throws Exception, NoSuchElementException, IllegalStateException {
        log.info("ftpPool 取出连接前的个数为:"+getNumIdle());

        FTPClient client = blockingQueue.poll(1, TimeUnit.MINUTES);
        log.info("ftpPool 取出连接后的个数为:"+getNumIdle());
        if (client == null) {
            this.addObject();
            log.info("client==null ");
            client=borrowObject();
        } else if (!ftpFactory.validateObject(client)) {
            log.info("获取的连接对象无效");
            //invalidateObject(client);
            try {
                ftpFactory.destroyObject(client);
            } catch (Exception e) {
                //e.printStackTrace();
                log.info("invalidateObject error:{}",e);
            }
            //制造并添加新对象到池中
            log.info("添加新的连接对象到 ftpPool 中");
            this.addObject();

            client=borrowObject();
        }
        return client;

    }


    /**
     * 将 连接对象 返回给 ftpPool 中
     *
     * @param ftpClient
     * @throws Exception
     */
    @Override
    public void returnObject(FTPClient ftpClient) throws Exception {
        log.info("回收连接对象 前 的ftpPool连接数为:" + getNumIdle());
        if ((ftpClient != null)) {
            if (!blockingQueue.offer(ftpClient)) {
                try {
                    ftpFactory.destroyObject(ftpClient);
                    log.info("销毁无效连接对象");
                } catch (Exception e) {
                    throw e;
                }
            }else {
                log.info("回收连接对象 后 的ftpPool连接数为:" + getNumIdle());
            }

        }
    }


    /**
     * 删除失效的 ftp连接对象
     *
     * @param ftpClient
     * @throws Exception
     */
    @Override
    public void invalidateObject(FTPClient ftpClient) throws Exception {
        blockingQueue.remove(ftpClient);
    }


    /**
     * 给 ftpPool 中添加一个新的连接对象,且在超时后会从 ftpPool 中删去
     *
     * @throws Exception
     * @throws IllegalStateException
     * @throws UnsupportedOperationException
     */
    @Override
    public void addObject() throws Exception, IllegalStateException, UnsupportedOperationException {
        //超时时间20秒
        blockingQueue.offer(ftpFactory.makeObject(), 20000, TimeUnit.MINUTES);
    }


    /**
     *获取空闲的 ftp连接数
     *
     * @return
     * @throws UnsupportedOperationException
     */
    @Override
    public int getNumIdle() throws UnsupportedOperationException {
        return blockingQueue.size();
    }


    /**
     * 获取正在被使用的 ftp连接数
     *
     * @return
     * @throws UnsupportedOperationException
     */
    @Override
    public int getNumActive() throws UnsupportedOperationException {
        return ftpConstant.getDefultPoolSize() - getNumIdle();
    }

    @Override
    public void clear() throws Exception, UnsupportedOperationException {

    }


    /**
     * 关闭连接池
     *
     * @throws Exception
     */
    @Override
    public void close() throws Exception {
        try {
            while (blockingQueue.iterator().hasNext()) {
                FTPClient client = blockingQueue.take();
                ftpFactory.destroyObject(client);
            }
        } catch (Exception e) {
            log.error("关闭连接池错误:", e);
        }
    }

    @Override
    public void setFactory(PoolableObjectFactory<FTPClient> poolableObjectFactory) throws IllegalStateException, UnsupportedOperationException {

    }
}

5、编写文件上传下载的方法

package com.hwhy.hainandatacheck.common.util.ftp;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.charset.StandardCharsets;

/**
 * ftp文件上传、下载、删除工具类
 */
@Slf4j
@Component
public class FtpUtils {

    public static FtpPool ftpPool;

    static {
        ftpPool = new FtpPool();
    }

 /**
     * 上传文件
     *
     * @param filePath    文件路径
     * @param fileName    文件名
     * @param inputStream 输入文件流
     * @return
     */
    public static boolean uploadFile(String filePath, String fileName, InputStream inputStream) throws Exception {
        //连接服务器
        //FTPClient ftpClient = initFtpClient();
        FTPClient ftpClient = ftpPool.borrowObject();
        try {
            log.info("开始上传文件");
            //设置传输类型
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            //创建子目录
            ftpClient.makeDirectory(filePath);
            //更改当前目录
            ftpClient.changeWorkingDirectory(filePath);
            //写入文件
            boolean b = ftpClient.storeFile(fileName, inputStream);
            if (b) {
                log.info("上传文件成功");
            } else {
                log.info("上传文件失败");
            }
            return b;
        } catch (Exception e) {
            log.info("上传文件失败");
            e.printStackTrace();
            return false;
        } finally {
            //closeFtp(ftpClient);
            ftpPool.returnObject(ftpClient);
        }
    }

/**
     * 下载文件
     *
     * @param remotePath FTP服务器上的相对路径
     * @param fileName   要下载的文件名
     * @return
     */
    public static InputStream downFile(String remotePath, String fileName) throws Exception {
        //连接服务器
        //FTPClient ftpClient = initFtpClient();
        FTPClient ftpClient = ftpPool.borrowObject();

        try {
            // 转移到FTP服务器目录
            ftpClient.changeWorkingDirectory(remotePath);
            FTPFile[] ftpFiles = ftpClient.listFiles();
            for (FTPFile ftpFile : ftpFiles) {
                if (ftpFile.getName().equals(fileName)) {
                    InputStream inputStream = ftpClient.retrieveFileStream(ftpFile.getName());
                    if (inputStream != null) {
                        return inputStream;
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //closeFtp(ftpClient);
            ftpPool.returnObject(ftpClient);
        }
        return null;
    }

}

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用SpringBoot实现FTP连接池的步骤: 1.在pom.xml文件中添加以下依赖: ```xml <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-pool2</artifactId> <version>2.7.0</version> </dependency> <dependency> <groupId>commons-net</groupId> <artifactId>commons-net</artifactId> <version>3.6</version> </dependency> ``` 2.创建FTP连接池配置类FtpClientPoolConfig,配置连接池的最大、最小连接数、连接超时时间等参数。 ```java @Configuration @ConfigurationProperties(prefix = "ftp.pool") @Data public class FtpClientPoolConfig { private int maxTotal; private int maxIdle; private int minIdle; private long maxWaitMillis; private boolean testOnBorrow; private boolean testOnReturn; private boolean testWhileIdle; private long timeBetweenEvictionRunsMillis; private int numTestsPerEvictionRun; private long minEvictableIdleTimeMillis; } ``` 3.创建FTP连接池FtpClientPool,使用Apache Commons Pool2实现连接池。 ```java @Component public class FtpClientPool extends GenericObjectPool<FtpClient> { public FtpClientPool(FtpClientFactory factory, FtpClientPoolConfig config) { super(factory, new GenericObjectPoolConfig()); this.setMaxTotal(config.getMaxTotal()); this.setMaxIdle(config.getMaxIdle()); this.setMinIdle(config.getMinIdle()); this.setMaxWaitMillis(config.getMaxWaitMillis()); this.setTestOnBorrow(config.isTestOnBorrow()); this.setTestOnReturn(config.isTestOnReturn()); this.setTestWhileIdle(config.isTestWhileIdle()); this.setTimeBetweenEvictionRunsMillis(config.getTimeBetweenEvictionRunsMillis()); this.setNumTestsPerEvictionRun(config.getNumTestsPerEvictionRun()); this.setMinEvictableIdleTimeMillis(config.getMinEvictableIdleTimeMillis()); } } ``` 4.创建FTP连接池工厂类FtpClientFactory,用于创建FTP连接对象。 ```java @Component public class FtpClientFactory extends BasePooledObjectFactory<FtpClient> { private FtpClientProperties properties; public FtpClientFactory(FtpClientProperties properties) { this.properties = properties; } @Override public FtpClient create() throws Exception { FtpClient ftpClient = new FtpClient(); ftpClient.connect(properties.getHost(), properties.getPort()); ftpClient.login(properties.getUsername(), properties.getPassword()); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); ftpClient.setBufferSize(properties.getBufferSize()); ftpClient.setControlEncoding(properties.getEncoding()); ftpClient.enterLocalPassiveMode(); return ftpClient; } @Override public PooledObject<FtpClient> wrap(FtpClient ftpClient) { return new DefaultPooledObject<>(ftpClient); } @Override public void destroyObject(PooledObject<FtpClient> p) throws Exception { FtpClient ftpClient = p.getObject(); if (ftpClient.isConnected()) { ftpClient.logout(); ftpClient.disconnect(); } } @Override public boolean validateObject(PooledObject<FtpClient> p) { FtpClient ftpClient = p.getObject(); try { return ftpClient.sendNoOp(); } catch (IOException e) { return false; } } } ``` 5.创建FTP连接池属性类FtpClientProperties,用于配置FTP连接的相关参数。 ```java @ConfigurationProperties(prefix = "ftp") @Data public class FtpClientProperties { private String host; private int port; private String username; private String password; private int bufferSize; private String encoding; } ``` 6.在application.yml文件中配置FTP连接池的相关参数。 ```yaml ftp: host: ftp.example.com port: 21 username: username password: password bufferSize: 1024 encoding: UTF-8 ftp: pool: maxTotal: 10 maxIdle: 5 minIdle: 1 maxWaitMillis: 3000 testOnBorrow: true testOnReturn: false testWhileIdle: true timeBetweenEvictionRunsMillis: 60000 numTestsPerEvictionRun: -1 minEvictableIdleTimeMillis: 1800000 ``` 7.在需要使用FTP连接的地方,注入FtpClientPool对象,从连接池中获取FTP连接对象。 ```java @Service public class FtpService { @Autowired private FtpClientPool ftpClientPool; public void uploadFile(String remotePath, String fileName, InputStream inputStream) throws Exception { FtpClient ftpClient = ftpClientPool.borrowObject(); try { ftpClient.changeWorkingDirectory(remotePath); ftpClient.storeFile(fileName, inputStream); } finally { ftpClientPool.returnObject(ftpClient); } } } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值