package cn.timer.api.config.sftp; import cn.timer.api.aspect.ChannelSftpFactory; import com.jcraft.jsch.ChannelSftp; import lombok.Data; import org.apache.commons.pool2.impl.AbandonedConfig; import org.apache.commons.pool2.impl.GenericObjectPool; import org.apache.commons.pool2.impl.GenericObjectPoolConfig; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Configuration; import org.springframework.stereotype.Component; /** * @author wuqingjun * @email 284718418@qq.com * @date 2021/12/28 */ @Configuration @Component @Data public class SftpConfiguration { //连接池 public GenericObjectPool<ChannelSftp> channelSftpPool; //host @Value("${sftp.client.host}") private String host; //端口 @Value("${sftp.client.port}") private Integer port; //协议 @Value("${sftp.client.protocol}") private String protocol; //用户 @Value("${sftp.client.username}") private String username; //密码 @Value("${sftp.client.password}") private String password; //根路径 @Value("${sftp.client.root}") private String root; @Value("${sftp.client.sessionStrictHostKeyChecking}") private String sessionStrictHostKeyChecking; //session超时时间 @Value("${sftp.client.sessionConnectTimeout}") private Integer sessionConnectTimeout; //channel超时时间 @Value("${sftp.client.channelConnectedTimeout}") private Integer channelConnectedTimeout; //图片服务url @Value("${sftp.client.serverUrl}") private String serverUrl; @Value("${sftp.client.targetPath}") private String targetPath; @Value("${sftp.client.reservedName}") private boolean reservedName; @Value("${config-8timer.file-address.type}") public String fileAddress; /** * @Title: getSftpSocket * @Description: 获取连接 * @param: @return * @return: ChannelSftp * @throws */ public ChannelSftp getSftpSocket(){ try { if(null == this.channelSftpPool){ initPool(); } return this.channelSftpPool.borrowObject(); } catch (Exception e) { e.printStackTrace(); } return null; } /** * @Title: returnSftpSocket * @Description: 归还连接 * @param: @param sftp * @return: void * @throws */ public void returnSftpSocket(ChannelSftp sftp){ this.channelSftpPool.returnObject(sftp); } /** * @Title: initPool * @Description: 初始化连接池 * @param: * @return: void * @throws */ private void initPool(){ GenericObjectPoolConfig config=new GenericObjectPoolConfig(); config.setMinIdle(10); config.setMaxTotal(10); config.setMaxWaitMillis(30000); this.channelSftpPool = new GenericObjectPool<>(new ChannelSftpFactory(host, port, protocol, username, password, sessionStrictHostKeyChecking, sessionConnectTimeout, channelConnectedTimeout),config); AbandonedConfig abandonedConfig = new AbandonedConfig(); //在Maintenance的时候检查是否有泄漏 abandonedConfig.setRemoveAbandonedOnMaintenance(true); //borrow 的时候检查泄漏 abandonedConfig.setRemoveAbandonedOnBorrow(true); //如果一个对象borrow之后60秒还没有返还给pool,认为是泄漏的对象 abandonedConfig.setRemoveAbandonedTimeout(60); this.channelSftpPool.setAbandonedConfig(abandonedConfig); //30秒运行一次维护任务 this.channelSftpPool.setTimeBetweenEvictionRunsMillis(30000); } }