java sftp连接池_使用连接池和JSCH

首先,您需要实现负责池化对象生命周期的池对象工厂:

public class ChannelSftpConnectionsFactory extends BasePooledObjectFactory {

private SessionManager sessionManager;

public ChannelSftpConnectionsFactory(final SessionManager sessionManager) {

this.sessionManager = sessionManager;

}

//Create and open channel

@Override

public ChannelSftp create() throws JSchException {

ChannelSftp channelSftp = (ChannelSftp) sessionManager.getSession().openChannel("sftp");

channelSftp.connect();

return channelSftp;

}

//wrapping

@Override

public PooledObject wrap(final ChannelSftp channelSftp) {

return new DefaultPooledObject<>(channelSftp);

}

@Override

//disconnect channel on destroy

public void destroyObject(final PooledObject pooledObject) {

ChannelSftp sftp = pooledObject.getObject();

disconnectChannel(sftp);

}

void disconnectChannel(final ChannelSftp sftp) {

if (sftp.isConnected()) {

sftp.disconnect();

}

}

@Override

//reset channel current folder to home if someone was walking on another folders

public void passivateObject(final PooledObject p) {

ChannelSftp sftp = p.getObject();

try {

sftp.cd(sftp.getHome());

} catch (SftpException ex) {

log.error("Could not reset channel to home folder, closing it");

disconnectChannel(sftp);

}

}

@Override

//validate object before it is borrowed from pool. If false object will be removed from pool

public boolean validateObject(final PooledObject p) {

ChannelSftp sftp = p.getObject();

return sftp.isConnected() && !sftp.isClosed();

}

}

现在您可以使用配置的工厂创建池:

ObjectPool createPool(final SessionManager sessionManager, final GenericObjectPoolConfig poolConfig) {

return PoolUtils.synchronizedPool(new GenericObjectPool<>(buildFactory(sessionManager), poolConfig));

}

PooledObjectFactory buildFactory(final SessionManager sessionManager) {

return PoolUtils.synchronizedPooledFactory(new ChannelSftpConnectionsFactory(sessionManager));

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值