您的位置:首页 > 编程语言

JedisPool使用原理和源代码

2015-07-03 23:21 225 查看

1,JedisPool的使用

<!--连接池的配置信息--><beanid="jedisConfig"class="redis.clients.jedis.JedisPoolConfig"><!--说明一个pool可以有多少个Jedis实例--><propertyname="maxActive"value="10"/><!--最大Idle--><propertyname="maxIdle"value="5"/><!--最小Idle--><propertyname="minIdle"value="1"/><!--获得一个jedis实例的时候是否检查连接可用性(ping())--><propertyname="testOnBorrow"value="true"/><!--return一个jedis实例给pool时,是否检查连接可用性(ping())--><propertyname="testOnReturn"value="true"/><!--idle状态监测用异步线程evict进行检查,--><propertyname="testWhileIdle"value="true"/><!--一次最多evict的pool里的jedis实例个数--><propertyname="numTestsPerEvictionRun"value="10"/><!--testidle线程的时间间隔--><propertyname="timeBetweenEvictionRunsMillis"value="60000"/><!--最大等待wait时间--><propertyname="maxWait"value="3000"/><propertyname="whenExhaustedAction"value=""/>
//WHEN_EXHAUSTED_FAIL=0;直接抛出异常thrownewNoSuchElementException("Poolexhausted");
//WHEN_EXHAUSTED_BLOCK=1;borrowObject()将会阻塞,直到有可用新的或者空闲的object为止,或者如果配置了maxWait,
//如果请求阻塞超时,将抛出NoSuchElementException.如果maxWait为负数,请求将会无限制的阻
//塞下去,默认配置。
//WHEN_EXHAUSTED_GROW=2;borrowObject()将会继续创建新的对象,并返回,因此,pool维护的对像数将超出maxActive;
//
</bean>



publicStringset(Stringkey,Stringvalue){
Jedisjedis=null;
booleansuccess=true;
try{
jedis=this.pool.getResource();
returnjedis.set(key,value);
}catch(JedisExceptione){
success=false;
if(jedis!=null){
pool.returnBrokenResource(jedis);
}
throwe;
}finally{
if(success&&jedis!=null){
this.pool.returnResource(jedis);
}
}
}

获取Jedis

pool.getResource();

这个可以直接看Pool的getResource方法,

最终还是GenericObjectPool的borrowObject()方法借用对象

@SuppressWarnings("unchecked")
publicTgetResource(){
try{
return(T)internalPool.borrowObject();
}catch(Exceptione){
thrownewJedisConnectionException(
"Couldnotgetaresourcefromthepool",e);
}
}

用完归还,调用的是GenericObjectPool的returnObject()方法

pool.returnResource(jedis)

//JedisPool.java

publicvoidreturnResource(finalBinaryJedisresource){
returnResourceObject(resource);
}
//Pool.java

publicvoidreturnResourceObject(finalObjectresource){
try{
internalPool.returnObject(resource);
}catch(Exceptione){
thrownewJedisException(
"Couldnotreturntheresourcetothepool",e);
}
}

出错,调用的是GenericObjectPool的invalidateObject()方法

最后在JedisFactory的destroyObject()中调用jedis.quit()请求Server关闭连接

pool.returnBrokenResource(jedis)
//JedisPool.java

publicvoidreturnBrokenResource(finalBinaryJedisresource){
returnBrokenResourceObject(resource);
}
//Pool.javaprotectedvoidreturnBrokenResourceObject(finalObjectresource){
try{
//失效
internalPool.invalidateObject(resource);
}catch(Exceptione){
thrownewJedisException(
"Couldnotreturntheresourcetothepool",e);
}
}
//GenericObjectPool

publicvoidinvalidateObject(Objectobj)
throwsException
{
try
{
if(this._factory!=null)
this._factory.destroyObject(obj);
}
finally{
synchronized(this){
this._numActive-=1;
allocate();
}
}
}
//JedisFactory

publicvoiddestroyObject(finalObjectobj)throwsException{
if(objinstanceofJedis){
finalJedisjedis=(Jedis)obj;
if(jedis.isConnected()){
try{
try{
jedis.quit();
}catch(Exceptione){
}
jedis.disconnect();
}catch(Exceptione){

}
}
}
}


JedisPool源代码

packageredis.clients.jedis;

importorg.apache.commons.pool.BasePoolableObjectFactory;
importorg.apache.commons.pool.impl.GenericObjectPool.Config;

importredis.clients.util.Pool;

publicclassJedisPoolextendsPool<Jedis>{publicJedisPool(finalConfigpoolConfig,finalStringhost){
this(poolConfig,host,Protocol.DEFAULT_PORT,Protocol.DEFAULT_TIMEOUT,null,Protocol.DEFAULT_DATABASE);
}

publicJedisPool(Stringhost,intport){
this(newConfig(),host,port,Protocol.DEFAULT_TIMEOUT,null,Protocol.DEFAULT_DATABASE);
}

publicJedisPool(finalStringhost){
this(host,Protocol.DEFAULT_PORT);
}

publicJedisPool(finalConfigpoolConfig,finalStringhost,intport,
inttimeout,finalStringpassword){
this(poolConfig,host,port,timeout,password,Protocol.DEFAULT_DATABASE);
}

publicJedisPool(finalConfigpoolConfig,finalStringhost,finalintport){
this(poolConfig,host,port,Protocol.DEFAULT_TIMEOUT,null,Protocol.DEFAULT_DATABASE);
}

publicJedisPool(finalConfigpoolConfig,finalStringhost,finalintport,finalinttimeout){
this(poolConfig,host,port,timeout,null,Protocol.DEFAULT_DATABASE);
}

publicJedisPool(finalConfigpoolConfig,finalStringhost,intport,inttimeout,finalStringpassword,
finalintdatabase){
super(poolConfig,newJedisFactory(host,port,timeout,password,database));
}

publicvoidreturnBrokenResource(finalBinaryJedisresource){
returnBrokenResourceObject(resource);
}

publicvoidreturnResource(finalBinaryJedisresource){
returnResourceObject(resource);
}

/**
*PoolableObjectFactorycustomimpl.
*/privatestaticclassJedisFactoryextendsBasePoolableObjectFactory{privatefinalStringhost;
privatefinalintport;
privatefinalinttimeout;
privatefinalStringpassword;
privatefinalintdatabase;

publicJedisFactory(finalStringhost,finalintport,
finalinttimeout,finalStringpassword,finalintdatabase){
super();
this.host=host;
this.port=port;
this.timeout=timeout;
this.password=password;
this.database=database;
}

publicObjectmakeObject()throwsException{
finalJedisjedis=newJedis(this.host,this.port,this.timeout);

jedis.connect();
if(null!=this.password){
jedis.auth(this.password);
}
if(database!=0){
jedis.select(database);
}

returnjedis;
}

publicvoiddestroyObject(finalObjectobj)throwsException{
if(objinstanceofJedis){
finalJedisjedis=(Jedis)obj;
if(jedis.isConnected()){
try{
try{
jedis.quit();
}catch(Exceptione){
}
jedis.disconnect();
}catch(Exceptione){

}
}
}
}

publicbooleanvalidateObject(finalObjectobj){
if(objinstanceofJedis){
finalJedisjedis=(Jedis)obj;
try{
returnjedis.isConnected();/*&&jedis.ping().equals("PONG");*/
}catch(finalExceptione){
returnfalse;
}
}else{
returnfalse;
}
}
}
}

其中JedisFactory继承自BasePoolableObjectFactory,只实现了3个方法

makeObject(),连接,newSocket()

destroyObject()--断开连接,

validateObject()--ping



Pool源代码

packageredis.clients.util;

importorg.apache.commons.pool.PoolableObjectFactory;
importorg.apache.commons.pool.impl.GenericObjectPool;

importredis.clients.jedis.exceptions.JedisConnectionException;
importredis.clients.jedis.exceptions.JedisException;

publicabstractclassPool<T>{privatefinalGenericObjectPoolinternalPool;

publicPool(finalGenericObjectPool.ConfigpoolConfig,
PoolableObjectFactoryfactory){
this.internalPool=newGenericObjectPool(factory,poolConfig);
}

@SuppressWarnings("unchecked")
publicTgetResource(){
try{
return(T)internalPool.borrowObject();
}catch(Exceptione){
thrownewJedisConnectionException(
"Couldnotgetaresourcefromthepool",e);
}
}

publicvoidreturnResourceObject(finalObjectresource){
try{
internalPool.returnObject(resource);
}catch(Exceptione){
thrownewJedisException(
"Couldnotreturntheresourcetothepool",e);
}
}

publicvoidreturnBrokenResource(finalTresource){
returnBrokenResourceObject(resource);
}

publicvoidreturnResource(finalTresource){
returnResourceObject(resource);
}

protectedvoidreturnBrokenResourceObject(finalObjectresource){
try{
//失效
internalPool.invalidateObject(resource);
}catch(Exceptione){
thrownewJedisException(
"Couldnotreturntheresourcetothepool",e);
}
}

publicvoiddestroy(){
try{
internalPool.close();
}catch(Exceptione){
thrownewJedisException("Couldnotdestroythepool",e);
}
}
}

JedisPoolConfig源代码

publicclassJedisPoolConfigextendsConfig{publicJedisPoolConfig(){
//defaultstomakeyourlifewithconnectionpooleasier:)
setTestWhileIdle(true);
setMinEvictableIdleTimeMillis(60000);
setTimeBetweenEvictionRunsMillis(30000);
setNumTestsPerEvictionRun(-1);
}

publicintgetMaxIdle(){
returnmaxIdle;
}

publicvoidsetMaxIdle(intmaxIdle){
this.maxIdle=maxIdle;
}

publicintgetMinIdle(){
returnminIdle;
}

publicvoidsetMinIdle(intminIdle){
this.minIdle=minIdle;
}

publicintgetMaxActive(){
returnmaxActive;
}

publicvoidsetMaxActive(intmaxActive){
this.maxActive=maxActive;
}

publiclonggetMaxWait(){
returnmaxWait;
}

publicvoidsetMaxWait(longmaxWait){
this.maxWait=maxWait;
}

publicbytegetWhenExhaustedAction(){
returnwhenExhaustedAction;
}

publicvoidsetWhenExhaustedAction(bytewhenExhaustedAction){
this.whenExhaustedAction=whenExhaustedAction;
}

publicbooleanisTestOnBorrow(){
returntestOnBorrow;
}

publicvoidsetTestOnBorrow(booleantestOnBorrow){
this.testOnBorrow=testOnBorrow;
}

publicbooleanisTestOnReturn(){
returntestOnReturn;
}

publicvoidsetTestOnReturn(booleantestOnReturn){
this.testOnReturn=testOnReturn;
}

publicbooleanisTestWhileIdle(){
returntestWhileIdle;
}

publicvoidsetTestWhileIdle(booleantestWhileIdle){
this.testWhileIdle=testWhileIdle;
}

publiclonggetTimeBetweenEvictionRunsMillis(){
returntimeBetweenEvictionRunsMillis;
}

publicvoidsetTimeBetweenEvictionRunsMillis(
longtimeBetweenEvictionRunsMillis){
this.timeBetweenEvictionRunsMillis=timeBetweenEvictionRunsMillis;
}

publicintgetNumTestsPerEvictionRun(){
returnnumTestsPerEvictionRun;
}

publicvoidsetNumTestsPerEvictionRun(intnumTestsPerEvictionRun){
this.numTestsPerEvictionRun=numTestsPerEvictionRun;
}

publiclonggetMinEvictableIdleTimeMillis(){
returnminEvictableIdleTimeMillis;
}

publicvoidsetMinEvictableIdleTimeMillis(longminEvictableIdleTimeMillis){
this.minEvictableIdleTimeMillis=minEvictableIdleTimeMillis;
}

publiclonggetSoftMinEvictableIdleTimeMillis(){
returnsoftMinEvictableIdleTimeMillis;
}

publicvoidsetSoftMinEvictableIdleTimeMillis(
longsoftMinEvictableIdleTimeMillis){
this.softMinEvictableIdleTimeMillis=softMinEvictableIdleTimeMillis;
}

}


                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: