java apache common pool2用法
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java apache common pool2用法相关的知识,希望对你有一定的参考价值。
// 首先实现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); // 创建对象池
以上是关于java apache common pool2用法的主要内容,如果未能解决你的问题,请参考以下文章
Spring Boot集成Redis启动失败Caused by: java.lang.ClassNotFoundException: org.apache.commons.pool2.impl.G
Spring Boot集成Redis启动失败Caused by: java.lang.ClassNotFoundException: org.apache.commons.pool2.impl.G
使用commons.pool2实现mysql连接池
[redis] The type org.apache.commons.pool2.impl.GenericObjectPoolConfig cannot be resolved.It is indi
commons.pool2 对象池的使用
通过线程池,从hbase中拿数据