FTPClientPool.java
2.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package com.viontech.ftp;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.pool2.impl.GenericObjectPool;
import java.io.IOException;
/**
* FTP 客户端连接池
*/
@Slf4j
public class FTPClientPool {
/**
* ftp客户端连接池
*/
private GenericObjectPool<FTPClient> pool;
/**
* ftp客户端工厂
*/
private FTPClientFactory clientFactory;
/**
* 构造函数中 注入一个bean
*
* @param clientFactory
*/
public FTPClientPool(FTPClientFactory clientFactory) {
this.clientFactory = clientFactory;
pool = new GenericObjectPool<FTPClient>(clientFactory, clientFactory.getFtpPoolConfig());
}
public FTPClientFactory getClientFactory() {
return clientFactory;
}
public GenericObjectPool<FTPClient> getPool() {
return pool;
}
/**
* 借 获取一个连接对象
*
* @return
*/
public FTPClient borrowObject() throws Exception {
FTPClient client = pool.borrowObject();
boolean valid = true;
try {
if (client.isConnected()) {
valid = client.sendNoOp();
} else {
valid = false;
}
} catch (IOException e) {
log.error("什么情况 刚刚获取的对象就不可用,", e);
e.printStackTrace();
valid = false;
}
if (!valid) {
//使池中的对象无效
try {
client.logout();
client.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
pool.invalidateObject(client);
}
return client;
}
/**
* 还 归还一个连接对象
*
* @param ftpClient
*/
public void returnObject(FTPClient ftpClient) {
if (ftpClient != null) {
try {
pool.returnObject(ftpClient);
} catch (Exception e) {
log.error("将FTP归还到FTP池中时发生异常", e);
}
}
}
}