首先,您需要實作負責池化對象生命周期的池對象工廠:
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));
}