Created
December 26, 2017 09:22
-
-
Save e7/3576d29ca2e1dcefd076b577b7c857b1 to your computer and use it in GitHub Desktop.
apache common pool2用法
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 首先实现PooledObjectFactory接口 | |
public interface PooledObjectFactory<T> { | |
PooledObject<T> makeObject() throws Exception; | |
void destroyObject(PooledObject<T> var1) throws Exception; | |
boolean validateObject(PooledObject<T> var1); | |
void activateObject(PooledObject<T> var1) throws Exception; | |
void passivateObject(PooledObject<T> var1) throws Exception; | |
} | |
public class BioConnectionFactory implements PooledObjectFactory<Socket> { | |
private int connectTimeout = 3 * 1000; // 连接超时时长(毫秒) | |
private SocketAddress targetAddr; | |
public BioConnectionFactory(String host, String port) { | |
int iport; | |
try { | |
iport = Integer.parseInt(port); | |
} catch (NumberFormatException e) { | |
iport = 3309; | |
} | |
this.targetAddr = new InetSocketAddress(host, iport); | |
} | |
@Override | |
public PooledObject<Socket> makeObject() throws Exception { | |
Socket sock = new Socket(); | |
sock.connect(this.targetAddr, this.connectTimeout); | |
sock.setSoTimeout(5 * 1000); // 设置read超时时长(毫秒) | |
sock.setKeepAlive(true); | |
return new DefaultPooledObject<>(sock); | |
} | |
@Override | |
public void destroyObject(PooledObject<Socket> obj) throws Exception { | |
Socket sock = obj.getObject(); | |
sock.shutdownOutput(); | |
sock.close(); | |
} | |
@Override | |
public boolean validateObject(PooledObject<Socket> pooledObject) { | |
Socket sock = pooledObject.getObject(); | |
try { | |
new SjsonbBioClient(sock).doAccess( | |
"{\"api\":\"ping\"}" | |
); | |
} catch (Exception e) { | |
e.printStackTrace(); | |
return false; | |
} | |
return true; | |
} | |
@Override | |
public void activateObject(PooledObject<Socket> pooledObject) throws Exception { | |
} | |
@Override | |
public void passivateObject(PooledObject<Socket> pooledObject) throws Exception { | |
} | |
} | |
// 使用 | |
GenericObjectPoolConfig pool_cnf = new GenericObjectPoolConfig(); // 对象池配置 | |
pool_cnf.setMaxTotal(10); // 最多10个对象 | |
pool_cnf.setMinIdle(1); // 至少一个空闲对象 | |
pool_cnf.setTestOnBorrow(true); // borrow前测试对象有效性 | |
new GenericObjectPool<>(new BioConnectionFactory(), pool_cnf); // 创建对象池 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment