客户端这边,如果每次都临时建立一个新的连接,那么连接的开销非常大。
业内常用的连接池组件是 Commons Pool2---版本 2.4.2
==================具体代码如下:[http://commons.apache.org/proper/commons-pool/examples.html]
package service.pool;
import org.apache.commons.pool2.BasePooledObjectFactory;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.impl.DefaultPooledObject;
import org.apache.thrift.transport.TSocket;
public class MyPoolFactory extends BasePooledObjectFactory<TSocket> {
private String ip;
private int port;
public MyPoolFactory(String string, int i) {
ip = string;
port = i;
}
@Override
public TSocket create() throws Exception {
// 初始化一个对象
TSocket ts = new TSocket(ip, port);
ts.open();
return ts;
}
@Override
public PooledObject<TSocket> wrap(TSocket ts) {
// 默认操作
return new DefaultPooledObject<TSocket>(ts);
}
/////////////////////////// 下面是5个生命周期
//makeObject默认
@Override
public void destroyObject(PooledObject<TSocket> p) throws Exception {
TSocket ts = p.getObject();
ts.close();
}
@Override
public boolean validateObject(PooledObject<TSocket> p) {
TSocket ts = p.getObject();
return ts.isOpen();
}
@Override
public void activateObject(PooledObject<TSocket> p) throws Exception {
// 返回给调用方时,做一些额外的操作
}
/**
* When an object is returned to the pool, clear the buffer.
*/
@Override
public void passivateObject(PooledObject<TSocket> tSocket) {
// 返回到pool时,做一些额外的操作
}
}
============================
具体使用时
// 设置传输通道,对于非阻塞服务,需要使用TFramedTransport,它将数据分块发送
GenericObjectPool pools = new GenericObjectPool<TSocket>(new MyPoolFactory("127.0.0.1", 7911));
GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
poolConfig.setBlockWhenExhausted(true);
poolConfig.setMaxWaitMillis(100);
poolConfig.setLifo(false);
poolConfig.setMaxIdle(50);//// 最大空闲连接数
poolConfig.setMinIdle(50);// 最小空闲连接数
poolConfig.setMaxTotal(100);// 整个池的最大值,最大连接数
poolConfig.setTestOnBorrow(true);
poolConfig.setTestOnCreate(true);
poolConfig.setTestOnReturn(true);
poolConfig.setTestWhileIdle(false);
pools.setConfig(poolConfig);
// 具体使用代码
TSocket ts = (TSocket) pools.borrowObject();
pools.returnObject(ts);