首先,您需要实现负责池化对象生命周期的池对象工厂:
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));
}