美文网首页
FTP连接池

FTP连接池

作者: 大树8026 | 来源:发表于2019-01-04 15:22 被阅读0次

    参考:https://blog.csdn.net/eakom/article/details/79038590
    一、引包

    <dependency>
    <groupId>commons-net</groupId>
    <artifactId>commons-net</artifactId>
    <version>3.5</version>
    </dependency>


    <dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-pool2</artifactId>
    <version>2.5.0</version>
    </dependency>

    二、概述:三个java类
    1、FTPClientPool
    重点在:
    public final static GenericObjectPool<FTPClient> ftpClientPool = new GenericObjectPool<FTPClient>(new FTPClientFactory(ftpConfig), poolConfig) ;

    2、FTPClientFactory
    用工厂去create()生成一个客户端

    3、FTPConfig
    ftp相关配置
    httpClient.properties

    #FTP连接池配置
    #最大数
    ftpClient_maxTotal=50
    #最小空闲
    ftpClient_minIdle=10
    #最大空闲
    ftpClient_maxIdle=100
    #最大等待时间
    ftpClient_maxWait=3000
    #池对象耗尽之后是否阻塞,maxWait<0时一直等待
    ftpClient_blockWhenExhausted=true
    #取对象是验证
    ftpClient_testOnBorrow=true
    #回收验证
    ftpClient_testOnReturn=true
    #创建时验证
    ftpClient_testOnCreate=true
    #空闲验证
    ftpClient_testWhileIdle=false
    #后进先出
    ftpClient_lifo=false
    \#FTP连接属性配置
    \#ip
    ftpClient_host=192.168.158.98
    \#端口
    ftpClient_port=21
    #登录名
    ftpClient_username=ftpadmin
    #密码
    ftpClient_pasword=eakom123456
    #连接是否为主动模式
    ftpClient_passiveMode=true
    #编码
    ftpClient_encoding=UTF-8
    #超时时间
    ftpClient_clientTimeout=600
    #线程数
    ftpClient_threaNum=1
    #文件传送类型
     #0=ASCII_FILE_TYPE(ASCII格式) 1=EBCDIC_FILE_TYPE 2=LOCAL_FILE_TYPE(二进制文件)  
    ftpClient_transferFileType=2
    #是否重命名
    ftpClient_renameUploaded=true
    #重新连接时间
    ftpClient_retryTimes=1200
    #缓存大小
    ftpClient_bufferSize=1024
    #默认进入的路径
    ftpClient_workingDirectory=/home/ftpadmin/
    

    三、代码

    1、FTPClientPool
    import org.apache.commons.net.ftp.FTPClient;
    import org.apache.commons.pool2.impl.GenericObjectPool;
    import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
    
    import basicdata.tool.PropertiesParserUtils;
    
    public class FTPClientPool{
        
        private static class FTPClientPoolInit{
            public static GenericObjectPoolConfig poolConfig;
            public static FTPConfig ftpConfig;
            static{
                poolConfig = new GenericObjectPoolConfig();
                poolConfig.setBlockWhenExhausted(Boolean.parseBoolean(PropertiesParserUtils.getProperty("ftpClient_blockWhenExhausted")));
                poolConfig.setMaxWaitMillis(Long.parseLong(PropertiesParserUtils.getProperty("ftpClient_maxWait")));
                poolConfig.setMinIdle(Integer.parseInt(PropertiesParserUtils.getProperty("ftpClient_minIdle")));
                poolConfig.setMaxIdle(Integer.parseInt(PropertiesParserUtils.getProperty("ftpClient_maxIdle")));
                poolConfig.setMaxTotal(Integer.parseInt(PropertiesParserUtils.getProperty("ftpClient_maxTotal")));
                poolConfig.setTestOnBorrow(Boolean.parseBoolean(PropertiesParserUtils.getProperty("ftpClient_testOnBorrow")));
                poolConfig.setTestOnReturn(Boolean.parseBoolean(PropertiesParserUtils.getProperty("ftpClient_testOnReturn")));
                poolConfig.setTestOnCreate(Boolean.parseBoolean(PropertiesParserUtils.getProperty("ftpClient_testOnCreate")));
                poolConfig.setTestWhileIdle(Boolean.parseBoolean(PropertiesParserUtils.getProperty("ftpClient_testWhileIdle")));
                poolConfig.setLifo(Boolean.parseBoolean(PropertiesParserUtils.getProperty("ftpClient_lifo")));
                
                ftpConfig=new FTPConfig();
                ftpConfig.setHost(PropertiesParserUtils.getProperty("ftpClient_host"));
                ftpConfig.setPort(Integer.parseInt(PropertiesParserUtils.getProperty("ftpClient_port")));
                ftpConfig.setUsername(PropertiesParserUtils.getProperty("ftpClient_username"));
                ftpConfig.setPassword(PropertiesParserUtils.getProperty("ftpClient_pasword"));
                ftpConfig.setClientTimeout(Integer.parseInt(PropertiesParserUtils.getProperty("ftpClient_clientTimeout")));
                ftpConfig.setEncoding(PropertiesParserUtils.getProperty("ftpClient_encoding"));
                ftpConfig.setWorkingDirectory(PropertiesParserUtils.getProperty("ftpClient_workingDirectory"));
                ftpConfig.setPassiveMode(Boolean.parseBoolean(PropertiesParserUtils.getProperty("ftpClient_passiveMode")));
                ftpConfig.setRenameUploaded(Boolean.parseBoolean(PropertiesParserUtils.getProperty("ftpClient_renameUploaded")));
                ftpConfig.setRetryTimes(Integer.parseInt(PropertiesParserUtils.getProperty("ftpClient_retryTimes")));
                ftpConfig.setTransferFileType(Integer.parseInt(PropertiesParserUtils.getProperty("ftpClient_transferFileType")));
                ftpConfig.setBufferSize(Integer.parseInt(PropertiesParserUtils.getProperty("ftpClient_bufferSize")));
            }
            public final static GenericObjectPool<FTPClient> ftpClientPool = new GenericObjectPool<FTPClient>(new FTPClientFactory(ftpConfig), poolConfig) ;
            
        }
        
        private FTPClientPool(){
            
        }
        public static GenericObjectPool<FTPClient> getInstance(){
            
            return FTPClientPoolInit.ftpClientPool;
        }
        public FTPClient borrowObject() throws Exception {
        /*  System.out.println("获取前");
            System.out.println("活动"+ftpClientPool.getNumActive());
            System.out.println("等待"+ftpClientPool.getNumWaiters());
            System.out.println("----------");*/
            return FTPClientPoolInit.ftpClientPool.borrowObject();
        }
        public void returnObject(FTPClient ftpClient) {
    
            /*System.out.println("归还前");
            System.out.println("活动"+ftpClientPool.getNumActive());
            System.out.println("等待"+ftpClientPool.getNumWaiters());
            System.out.println("----------");*/
            FTPClientPoolInit.ftpClientPool.returnObject(ftpClient);
            /*System.out.println("归还后");
            System.out.println("活动"+ftpClientPool.getNumActive());
            System.out.println("等待"+ftpClientPool.getNumWaiters());
            System.out.println("----------");*/
        }
    }
    
    
    
    2、FTPClientFactory 
    
    import java.io.IOException;
    
    import org.apache.commons.net.ftp.FTPClient;
    import org.apache.commons.net.ftp.FTPReply;
    import org.apache.commons.pool2.BasePooledObjectFactory;
    import org.apache.commons.pool2.PooledObject;
    import org.apache.commons.pool2.impl.DefaultPooledObject;
    
    public class FTPClientFactory extends BasePooledObjectFactory<FTPClient> {
        public static logger = LoggerFactory.getLogger();   
        private FTPConfig ftpConfig;
    
        public FTPClientFactory(FTPConfig ftpConfig) {
            this.ftpConfig = ftpConfig;
        }
        /**
         * 新建对象
         */
        @Override
        public FTPClient create() throws Exception {
            FTPClient ftpClient = new FTPClient();
            ftpClient.setConnectTimeout(ftpConfig.getClientTimeout());
            try {
                ftpClient.connect(ftpConfig.getHost(), ftpConfig.getPort());
                int reply = ftpClient.getReplyCode();
                if (!FTPReply.isPositiveCompletion(reply)) {
                    ftpClient.disconnect();
                    logger.error("FTPServer 拒绝连接");
                    return null;
                }
                boolean result = ftpClient.login(ftpConfig.getUsername(),ftpConfig.getPassword());
                if (!result) {
                    logger.error("ftpClient登陆失败!");
                    throw new Exception("ftpClient登陆失败! userName:"+ ftpConfig.getUsername() + " ; password:"
                            + ftpConfig.getPassword());
                }
                ftpClient.setFileType(ftpConfig.getTransferFileType());
                ftpClient.setBufferSize(ftpConfig.getBufferSize());
                ftpClient.setControlEncoding(ftpConfig.getEncoding());
                if (ftpConfig.getPassiveMode()) {
                    ftpClient.enterLocalPassiveMode();
                }
                ftpClient.changeWorkingDirectory(ftpConfig.getWorkingDirectory());
            } catch (IOException e) {
                logger.error("FTP连接失败:"+ e);
            }
            return ftpClient;
        }
    
        @Override
        public PooledObject<FTPClient> wrap(FTPClient ftpClient) {
            return new DefaultPooledObject<FTPClient>(ftpClient);
        }
    
        /**
         * 销毁对象
         */
        @Override
        public void destroyObject(PooledObject<FTPClient> p) throws Exception {
            FTPClient ftpClient = p.getObject();
            ftpClient.logout();
            super.destroyObject(p);
        }
    
        /**
         * 验证对象
         */
        @Override
        public boolean validateObject(PooledObject<FTPClient> p) {
            FTPClient ftpClient = p.getObject();
            boolean connect = false;
            try {
                connect = ftpClient.sendNoOp();
                if(connect){                
                    ftpClient.changeWorkingDirectory(ftpConfig.getWorkingDirectory());
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            return connect;
        }
    }
    
    3、FTPConfig
    package syn.osc.basicdata.tool.ftp;
    
    public class FTPConfig{
        private String host;
        private int port;
        private String username;
        private String password;
        private boolean passiveMode;
        private String encoding;
        private int clientTimeout;
        private int threadNum;
        private int transferFileType;
        private boolean renameUploaded;
        private int retryTimes;
        private int bufferSize;
        private String workingDirectory;
    
    
        public String getWorkingDirectory() {
            return workingDirectory;
        }
        public void setWorkingDirectory(String workingDirectory) {
            this.workingDirectory = workingDirectory;
        }
        public int getBufferSize() {
            return bufferSize;
        }
        public void setBufferSize(int bufferSize) {
            this.bufferSize = bufferSize;
        }
        public String getHost() {
            return host;
        }
        public void setHost(String host) {
            this.host = host;
        }
        public int getPort() {
            return port;
        }
        public void setPort(int port) {
            this.port = port;
        }
        public String getUsername() {
            return username;
        }
        public void setUsername(String username) {
            this.username = username;
        }
        public String getPassword() {
            return password;
        }
        public void setPassword(String password) {
            this.password = password;
        }
        public boolean getPassiveMode() {
            return passiveMode;
        }
        public void setPassiveMode(boolean passiveMode) {
            this.passiveMode = passiveMode;
        }
        public String getEncoding() {
            return encoding;
        }
        public void setEncoding(String encoding) {
            this.encoding = encoding;
        }
        public int getClientTimeout() {
            return clientTimeout;
        }
        public void setClientTimeout(int clientTimeout) {
            this.clientTimeout = clientTimeout;
        }
        public int getThreadNum() {
            return threadNum;
        }
        public void setThreadNum(int threadNum) {
            this.threadNum = threadNum;
        }
        public int getTransferFileType() {
            return transferFileType;
        }
        public void setTransferFileType(int transferFileType) {
            this.transferFileType = transferFileType;
        }
        public boolean isRenameUploaded() {
            return renameUploaded;
        }
        public void setRenameUploaded(boolean renameUploaded) {
            this.renameUploaded = renameUploaded;
        }
        public int getRetryTimes() {
            return retryTimes;
        }
        public void setRetryTimes(int retryTimes) {
            this.retryTimes = retryTimes;
        }
    }
    
    
    
    
    
    
        
    
    
    

    相关文章

      网友评论

          本文标题:FTP连接池

          本文链接:https://www.haomeiwen.com/subject/wizhrqtx.html