package com.dxhy.oss.utils;

import com.jcraft.jsch.ChannelSftp;
import lombok.Data;
import org.apache.commons.pool2.impl.GenericObjectPool;

@Data
public class SshPool {

    private GenericObjectPool<ChannelSftp> pool;

    public SshPool(SshFactory factory) {
        this.pool = new GenericObjectPool<>(factory, factory.getOssConfig().getPool());
    }

    /**
     * 获取一个sftp连接对象
     *
     * @return sftp连接对象
     */
    public ChannelSftp borrowObject() throws SftpPoolException {
        try {
            return pool.borrowObject();
        } catch (Exception e) {
            e.printStackTrace();
            throw new SftpPoolException("获取ftp连接失败", e);
        }
    }

    /**
     * 归还一个sftp连接对象
     *
     * @param channelSftp sftp连接对象
     */
    public void returnObject(ChannelSftp channelSftp) {
        if (channelSftp != null) {
            pool.returnObject(channelSftp);
        }
    }

}