FTPClientPool.java 2.12 KB
package com.viontech.ftp;


import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.pool2.impl.GenericObjectPool;

import java.io.IOException;

/**
 * FTP 客户端连接池
 */
@Slf4j
public class FTPClientPool {

    /**
     * ftp客户端连接池
     */
    private GenericObjectPool<FTPClient> pool;

    /**
     * ftp客户端工厂
     */
    private FTPClientFactory clientFactory;


    /**
     * 构造函数中 注入一个bean
     *
     * @param clientFactory
     */
    public FTPClientPool(FTPClientFactory clientFactory) {
        this.clientFactory = clientFactory;
        pool = new GenericObjectPool<FTPClient>(clientFactory, clientFactory.getFtpPoolConfig());

    }


    public FTPClientFactory getClientFactory() {
        return clientFactory;
    }


    public GenericObjectPool<FTPClient> getPool() {
        return pool;
    }


    /**
     * 借  获取一个连接对象
     *
     * @return
     */
    public FTPClient borrowObject() throws Exception {

        FTPClient client = pool.borrowObject();
        boolean valid = true;
        try {
            if (client.isConnected()) {
                valid = client.sendNoOp();
            } else {
                valid = false;
            }

        } catch (IOException e) {
            log.error("什么情况 刚刚获取的对象就不可用,", e);
            e.printStackTrace();
            valid = false;
        }
        if (!valid) {
            //使池中的对象无效
            try {
                client.logout();
                client.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }
            pool.invalidateObject(client);
        }

        return client;

    }

    /**
     * 还   归还一个连接对象
     *
     * @param ftpClient
     */
    public void returnObject(FTPClient ftpClient) {

        if (ftpClient != null) {
            try {
                pool.returnObject(ftpClient);
            } catch (Exception e) {
                log.error("将FTP归还到FTP池中时发生异常", e);
            }
        }
    }
}