SFTP连接池管理

//池对象
package com.starcoder.beans;

import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.Session;
import com.starcoder.config.SftpClientConfig;
import lombok.Data;

/**
 * @ClassName: SftpClient
 * @Description:
 * @Author wuzegao
 * @Date 2022/10/9
 * @Version 1.0
 */
@Data
public class SftpClient {
    private ChannelSftp channelSftp;
    private Session session;
    private SftpClientConfig sftpClientConfig;
}

// 对象池
package com.starcoder.beans;

import com.starcoder.config.SftpClientPoolConfig;
import com.starcoder.factory.SftpClientFactory;
import lombok.Data;
import org.apache.commons.pool2.ObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;

/**
 * @ClassName: SftpClientPool
 * @Description:
 * @Author wuzegao
 * @Date 2022/10/9
 * @Version 1.0
 */
@Data
public class SftpClientPool implements ObjectPool<SftpClient> {
    private SftpClientPoolConfig poolConfig;
    private SftpClientFactory factory;
    private GenericObjectPool<SftpClient> pool;

    public SftpClientPool(SftpClientPoolConfig poolConfig, SftpClientFactory factory) {
        this.poolConfig = poolConfig;
        this.factory = factory;
        this.pool = new GenericObjectPool<SftpClient>(factory,getConfig(poolConfig));
    }

    private GenericObjectPoolConfig<SftpClient> getConfig(SftpClientPoolConfig poolConfig) {
        GenericObjectPoolConfig<SftpClient> config = new GenericObjectPoolConfig<>();
        config.setMinIdle(poolConfig.getMinIdle());
        config.setMaxIdle(poolConfig.getMaxIdle());
        config.setMaxTotal(poolConfig.getMaxTotal());
        config.setTestOnBorrow(poolConfig.isTestOnBorrow());
        config.setTestOnReturn(poolConfig.isTestOnReturn());
        config.setTestWhileIdle(poolConfig.isTestWhileIdle());
        return config;
    }

    @Override
    public void addObject() throws Exception {
        pool.addObject();
    }

    @Override
    public SftpClient borrowObject() throws Exception {
        return pool.borrowObject();
    }

    @Override
    public void clear(){
        pool.clear();
    }

    @Override
    public void close() {
        pool.close();
    }

    @Override
    public int getNumActive() {
        return pool.getNumActive();
    }

    @Override
    public int getNumIdle() {
        return pool.getNumIdle();
    }

    @Override
    public void invalidateObject(SftpClient sftpClient) throws Exception {
        pool.invalidateObject(sftpClient);
    }

    @Override
    public void returnObject(SftpClient sftpClient) {
        pool.returnObject(sftpClient);
    }
}

//对象配置
package com.starcoder.config;

import lombok.Data;

/**
 * @ClassName: SftpConfig
 * @Description:
 * @Author wuzegao
 * @Date 2022/10/9
 * @Version 1.0
 */
@Data
public class SftpClientConfig{
    /**
     * 主机名
     */
    private String sftpname;
    /**
     * 主机ip
     */
    private String host;
    /**
     * 端口号
     */
    private int port;
    /**
     * 用户名
     */
    private String username;
    /**
     * 密码
     */
    private String password;
    /**
     * 路径
     */
    private String path;
    /**
     * 连接sftp服务器,默认超时时间30000
     */
    private int timeout = 30000;


}

// 池配置
package com.starcoder.config;

import com.starcoder.beans.SftpClient;
import lombok.Data;
import org.apache.commons.pool2.impl.GenericKeyedObjectPoolConfig;

/**
 * @ClassName: SftpClientPoolConfig
 * @Description:
 * @Author wuzegao
 * @Date 2022/10/10
 * @Version 1.0
 */
@Data
public class SftpClientPoolConfig extends GenericKeyedObjectPoolConfig<SftpClient> {
    private int maxTotal;
    private int maxIdle;
    private int minIdle;
    private boolean lifo;
    private boolean fairness;
    private long maxWaitMillis;
    private long minEvictableIdleTimeMillis;
    private long evictorShutdownTimeoutMillis;
    private long softMinEvictableIdleTimeMillis;
    private int numTestsPerEvictionRun;
    private String evictionPolicyClassName;
    private boolean testOnCreate;
    private boolean testOnBorrow;
    private boolean testOnReturn;
    private boolean testWhileIdle;
    private long timeBetweenEvictionRunsMillis;
    private boolean blockWhenExhausted;
    private boolean jmxEnabled;
    private String jmxNamePrefix;
    private String jmxNameBase;
    /**
     * 获取连接重试次数
     */
    private int retryCount;
}


// 工厂类
package com.starcoder.factory;

import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.starcoder.beans.SftpClient;
import com.starcoder.config.SftpClientConfig;
import com.starcoder.config.SftpClientPoolConfig;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.pool2.BasePooledObjectFactory;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.impl.DefaultPooledObject;

import java.util.Properties;

/**
 * @ClassName: SftpClientFactory
 * @Description:
 * @Author wuzegao
 * @Date 2022/10/10
 * @Version 1.0
 */
@Data
public class SftpClientFactory extends BasePooledObjectFactory<SftpClient> {
    private SftpClientConfig clientConfig;
    private SftpClientPoolConfig poolConfig;

    @Override
    public SftpClient create() throws Exception {
        SftpClient sftpClient = null;
        ChannelSftp channel = null;
        // 用户名密码不能为空
        if (StringUtils.isBlank(clientConfig.getUsername()) || StringUtils.isBlank(clientConfig.getPassword())) {
            return null;
        }

        JSch jsch = new JSch();
        Session sshSession = jsch.getSession(clientConfig.getUsername(), clientConfig.getHost(), clientConfig.getPort());
        sshSession.setPassword(clientConfig.getPassword());
        Properties sshConfig = new Properties();
        // “StrictHostKeyChecking”如果设置成“yes”,ssh就不会自动把计算机的密匙加入“$HOME/.ssh/known_hosts”文件,并且一旦计算机的密匙发生了变化,就拒绝连接。
        sshConfig.put("StrictHostKeyChecking", "no");
        sshSession.setConfig(sshConfig);
        sshSession.connect();
        channel = (ChannelSftp) sshSession.openChannel("sftp");
        channel.connect();
        sftpClient = new SftpClient();
        sftpClient.setChannelSftp(channel);
        sftpClient.setSession(sshSession);
        sftpClient.setSftpClientConfig(clientConfig);
        return sftpClient;
    }

    @Override
    public PooledObject<SftpClient> wrap(SftpClient sftpClient) {
        return new DefaultPooledObject<>(sftpClient);
    }
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
要在Spring Boot中配置SFTP连接,可以使用Apache Commons VFS2库。 首先,您需要在pom.xml文件中添加以下依赖项: ```xml <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-vfs2</artifactId> <version>2.7.0</version> </dependency> ``` 然后,您可以配置SFTP连接。以下是一个例子: ```java @Configuration public class SftpConfig { @Value("${sftp.host}") private String sftpHost; @Value("${sftp.port}") private int sftpPort; @Value("${sftp.username}") private String sftpUsername; @Value("${sftp.password}") private String sftpPassword; @Value("${sftp.poolSize}") private int sftpPoolSize; @Bean public GenericObjectPool<ChannelSftp> sftpPool() throws JSchException { JSch jsch = new JSch(); Session session = jsch.getSession(sftpUsername, sftpHost, sftpPort); session.setPassword(sftpPassword); session.setConfig("StrictHostKeyChecking", "no"); session.connect(); SftpConnectionFactory factory = new SftpConnectionFactory(session); GenericObjectPoolConfig<ChannelSftp> config = new GenericObjectPoolConfig<>(); config.setMaxTotal(sftpPoolSize); config.setTestOnBorrow(true); return new GenericObjectPool<>(factory, config); } } ``` 在这个例子中,我们使用JSch库连接SFTP服务器,并使用Apache Commons Pool库来创建连接。您需要在application.properties或application.yml文件中设置SFTP连接属性。 ```yaml sftp: host: sftp.example.com port: 22 username: username password: password poolSize: 10 ``` 现在,您可以使用sftpPool bean注入连接,并使用连接中的连接执行SFTP操作。例如: ```java @Service public class SftpService { private final GenericObjectPool<ChannelSftp> sftpPool; public SftpService(GenericObjectPool<ChannelSftp> sftpPool) { this.sftpPool = sftpPool; } public void downloadFile(String remotePath, String localPath) throws Exception { ChannelSftp sftp = sftpPool.borrowObject(); try { sftp.get(remotePath, localPath); } finally { sftpPool.returnObject(sftp); } } } ``` 在这个例子中,我们使用borrowObject方法从中获取一个连接。执行操作后,我们使用returnObject方法将连接返回到中。 这是一个简单的示例,您可以根据您的需求进行修改。希望对您有所帮助!

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值