GitHub : github.com/jayknoxqu/f…html
频繁的创建和关闭链接,会极大的下降系统的性能,而链接池会在初始化的时候会建立必定数量的链接,每次访问只需从链接池里获取链接,使用完毕后再放回链接池,并非直接关闭链接,这样能够保证程序重复使用同一个链接而不须要每次访问都创建和关闭链接, 从而提升系统性能。java
<!-- 使用commons-pool2 实现ftp链接池 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
<version>2.5.0</version>
</dependency>
<!-- 引入FTPClient做为池化对象 -->
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.6</version>
</dependency>
复制代码
PooledObject(池化对象) PooledObjectFactory(对象工厂) ObjectPool (对象池)
git
对应为:github
FTPClient(池化对象) FTPClientFactory(对象工厂) FTPClientPool(对象池)
apache
关系图:bash
咱们已经有现成的池化对象(FtpClient)了,只须要添加配置便可app
@ConfigurationProperties(ignoreUnknownFields = false, prefix = "ftp.client")
public class FtpClientProperties {
// ftp地址
private String host;
// 端口号
private Integer port = 21;
// 登陆用户
private String username;
// 登陆密码
private String password;
// 被动模式
private boolean passiveMode = false;
// 编码
private String encoding = "UTF-8";
// 链接超时时间(秒)
private Integer connectTimeout;
// 缓冲大小
private Integer bufferSize = 1024;
// 传输文件类型
private Integer transferFileType;
}
复制代码
application.properties配置为:ide
ftp.client.host=127.0.0.1
ftp.client.port=22
ftp.client.username=root
ftp.client.password=root
ftp.client.encoding=utf-8
ftp.client.passiveMode=false
ftp.client.connectTimeout=30000
复制代码
在commons-pool2中有两种工厂:PooledObjectFactory 和KeyedPooledObjectFactory,咱们使用前者。性能
public interface PooledObjectFactory<T> {
//建立对象
PooledObject<T> makeObject();
//激活对象
void activateObject(PooledObject<T> obj);
//钝化对象
void passivateObject(PooledObject<T> obj);
//验证对象
boolean validateObject(PooledObject<T> obj);
//销毁对象
void destroyObject(PooledObject<T> obj);
}
复制代码
建立FtpClientFactory只须要继承BasePooledObjectFactory这个抽象类 ,而它则实现了PooledObjectFactorythis
public class FtpClientFactory extends BasePooledObjectFactory<FTPClient> {
private FtpClientProperties config;
public FtpClientFactory(FtpClientProperties config) {
this.config = config;
}
/** * 建立FtpClient对象 */
@Override
public FTPClient create() {
FTPClient ftpClient = new FTPClient();
ftpClient.setControlEncoding(config.getEncoding());
ftpClient.setConnectTimeout(config.getConnectTimeout());
try {
ftpClient.connect(config.getHost(), config.getPort());
int replyCode = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(replyCode)) {
ftpClient.disconnect();
log.warn("FTPServer refused connection,replyCode:{}", replyCode);
return null;
}
if (!ftpClient.login(config.getUsername(), config.getPassword())) {
log.warn("ftpClient login failed... username is {}; password: {}", config.getUsername(), config.getPassword());
}
ftpClient.setBufferSize(config.getBufferSize());
ftpClient.setFileType(config.getTransferFileType());
if (config.isPassiveMode()) {
ftpClient.enterLocalPassiveMode();
}
} catch (IOException e) {
log.error("create ftp connection failed...", e);
}
return ftpClient;
}
/** * 用PooledObject封装对象放入池中 */
@Override
public PooledObject<FTPClient> wrap(FTPClient ftpClient) {
return new DefaultPooledObject<>(ftpClient);
}
/** * 销毁FtpClient对象 */
@Override
public void destroyObject(PooledObject<FTPClient> ftpPooled) {
if (ftpPooled == null) {
return;
}
FTPClient ftpClient = ftpPooled.getObject();
try {
if (ftpClient.isConnected()) {
ftpClient.logout();
}
} catch (IOException io) {
log.error("ftp client logout failed...{}", io);
} finally {
try {
ftpClient.disconnect();
} catch (IOException io) {
log.error("close ftp client failed...{}", io);
}
}
}
/** * 验证FtpClient对象 */
@Override
public boolean validateObject(PooledObject<FTPClient> ftpPooled) {
try {
FTPClient ftpClient = ftpPooled.getObject();
return ftpClient.sendNoOp();
} catch (IOException e) {
log.error("Failed to validate client: {}", e);
}
return false;
}
}
复制代码
在commons-pool2中预设了三个能够直接使用的对象池:GenericObjectPool、GenericKeyedObjectPool和SoftReferenceObjectPool
示列:
GenericObjectPool<FTPClient> ftpClientPool = new GenericObjectPool<>(new FtpClientFactory());
复制代码
咱们也能够本身实现一个链接池:
public interface ObjectPool<T> extends Closeable {
// 从池中获取一个对象
T borrowObject();
// 归还一个对象到池中
void returnObject(T obj);
// 废弃一个失效的对象
void invalidateObject(T obj);
// 添加对象到池
void addObject();
// 清空对象池
void clear();
// 关闭对象池
void close();
}
复制代码
经过继承BaseObjectPool去实现ObjectPool
public class FtpClientPool extends BaseObjectPool<FTPClient> {
private static final int DEFAULT_POOL_SIZE = 8;
private final BlockingQueue<FTPClient> ftpBlockingQueue;
private final FtpClientFactory ftpClientFactory;
/** * 初始化链接池,须要注入一个工厂来提供FTPClient实例 * * @param ftpClientFactory ftp工厂 * @throws Exception */
public FtpClientPool(FtpClientFactory ftpClientFactory) throws Exception {
this(DEFAULT_POOL_SIZE, ftpClientFactory);
}
public FtpClientPool(int poolSize, FtpClientFactory factory) throws Exception {
this.ftpClientFactory = factory;
ftpBlockingQueue = new ArrayBlockingQueue<>(poolSize);
initPool(poolSize);
}
/** * 初始化链接池,须要注入一个工厂来提供FTPClient实例 * * @param maxPoolSize 最大链接数 * @throws Exception */
private void initPool(int maxPoolSize) throws Exception {
for (int i = 0; i < maxPoolSize; i++) {
// 往池中添加对象
addObject();
}
}
/** * 从链接池中获取对象 */
@Override
public FTPClient borrowObject() throws Exception {
FTPClient client = ftpBlockingQueue.take();
if (ObjectUtils.isEmpty(client)) {
client = ftpClientFactory.create();
// 放入链接池
returnObject(client);
// 验证对象是否有效
} else if (!ftpClientFactory.validateObject(ftpClientFactory.wrap(client))) {
// 对无效的对象进行处理
invalidateObject(client);
// 建立新的对象
client = ftpClientFactory.create();
// 将新的对象放入链接池
returnObject(client);
}
return client;
}
/** * 返还对象到链接池中 */
@Override
public void returnObject(FTPClient client) {
try {
if (client != null && !ftpBlockingQueue.offer(client, 3, TimeUnit.SECONDS)) {
ftpClientFactory.destroyObject(ftpClientFactory.wrap(client));
}
} catch (InterruptedException e) {
log.error("return ftp client interrupted ...{}", e);
}
}
/** * 移除无效的对象 */
@Override
public void invalidateObject(FTPClient client) {
try {
client.changeWorkingDirectory("/");
} catch (IOException e) {
e.printStackTrace();
} finally {
ftpBlockingQueue.remove(client);
}
}
/** * 增长一个新的连接,超时失效 */
@Override
public void addObject() throws Exception {
// 插入对象到队列
ftpBlockingQueue.offer(ftpClientFactory.create(), 3, TimeUnit.SECONDS);
}
/** * 关闭链接池 */
@Override
public void close() {
try {
while (ftpBlockingQueue.iterator().hasNext()) {
FTPClient client = ftpBlockingQueue.take();
ftpClientFactory.destroyObject(ftpClientFactory.wrap(client));
}
} catch (Exception e) {
log.error("close ftp client ftpBlockingQueue failed...{}", e);
}
}
}
复制代码
不太同意本身去实现链接池,这样会带来额外的维护成本...
GitHub : github.com/jayknoxqu/f…
FTPClient链接池的实现: yq.aliyun.com/articles/59…
Apache Commons-pool2(整理): www.jianshu.com/p/b0189e01d…