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;
}
}
相关文章推荐
- Java可变长参数注意事项
- 2015070302 - EffactiveJava笔记 - 第52条 通过接口引用对象(2)
- ABP(现代ASP.NET样板开发框架)系列之11、ABP领域层——仓储(Repositories)
- php下phalcon 日志类Logger
- 一句话讲清楚什么是JavaEE
- 漂亮的C++控制台界面(格式化输入输出)
- [Java]学习笔记,随笔【十】
- Excel VBA 基础知识——用代码读写目标单元格
- 为什么用Spring来管理Hibernate?
- 如何在腾讯营销QQ获取在线咨询代码
- Django启航之开发环境搭建
- 黑马程序员---C语言基础---函数、参数、返回值
- DELPHI指针的使用
- FP-Growth算法python实现
- FP-Growth算法python实现
- spring+thymeleaf
- socket编程的一个简单的hello world程序
- 深入理解ASP.NET 5的依赖注入
- php计算两个日期时间差
- PHP 实现半个月内只能提交一单数据