JedisPool使用原理和原始碼

來源:互聯網
上載者:User

標籤:

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" /><!-- test idle 線程的時間間隔 --><propertyname="timeBetweenEvictionRunsMillis"value="60000" /><!--最大等待wait時間--><propertyname="maxWait"value="3000" /><propertyname="whenExhaustedAction"value="" />    //WHEN_EXHAUSTED_FAIL = 0; 直接拋出異常throw new NoSuchElementException("Pool exhausted");    //WHEN_EXHAUSTED_BLOCK = 1;borrowObject()將會阻塞,直到有可用新的或者閒置object為止,或者如果配置了maxWait,                            //如果請求阻塞逾時,將拋出NoSuchElementException.如果maxWait為負數,請求將會無限制的阻                            //塞下去,預設配置。    //WHEN_EXHAUSTED_GROW = 2;borrowObject()將會繼續建立新的對象,並返回,因此,pool維護的對像數將超出maxActive;                            //</bean>
 
 
public String set(String key, String value) {    Jedis jedis = null;    boolean success = true;    try {        jedis = this.pool.getResource();        return jedis.set(key, value);    }catch (JedisException e) {        success  = false;        if(jedis != null){            pool.returnBrokenResource(jedis);        }        throw e;    }finally{        if(success && jedis != null){            this.pool.returnResource(jedis);        }    }}

擷取Jedis

pool.getResource();

這個可以直接看Pool的getResource方法,

最終還是GenericObjectPool的borrowObject()方法借用對象

@SuppressWarnings("unchecked")public T getResource() {    try {        return (T) internalPool.borrowObject();    } catch (Exception e) {        throw new JedisConnectionException(                "Could not get a resource from the pool", e);    }}

用完歸還,調用的是GenericObjectPool的returnObject()方法

pool.returnResource(jedis)
//JedisPool.java
public void returnResource(final BinaryJedis resource) {    returnResourceObject(resource);}//Pool.java
publicvoid returnResourceObject(final Object resource) {try {    internalPool.returnObject(resource);} catch (Exception e) {    throw new JedisException(            "Could not return the resource to the pool", e);}}

出錯,調用的是GenericObjectPool的invalidateObject()方法

最後在JedisFactory的destroyObject()中調用jedis.quit()請求Server關閉串連

pool.returnBrokenResource(jedis)//JedisPool.java
public void returnBrokenResource(final BinaryJedis resource) {    returnBrokenResourceObject(resource);}//Pool.javaprotectedvoid returnBrokenResourceObject(final Object resource) {    try {        //失效        internalPool.invalidateObject(resource);    } catch (Exception e) {        thrownew JedisException(                "Could not return the resource to the pool", e);    }}//GenericObjectPool
publicvoid invalidateObject(Object obj)throws Exception{try{  if (this._factory != null)    this._factory.destroyObject(obj);}finally {  synchronized (this) {    this._numActive -= 1;    allocate();  }}}//JedisFactory
publicvoid destroyObject(final Object obj) throws Exception {    if (obj instanceof Jedis) {        final Jedis jedis = (Jedis) obj;        if (jedis.isConnected()) {            try {                try {                    jedis.quit();                } catch (Exception e) {                }                jedis.disconnect();            } catch (Exception e) {            }        }    }}

 

 

 

JedisPool原始碼

package redis.clients.jedis;import org.apache.commons.pool.BasePoolableObjectFactory;import org.apache.commons.pool.impl.GenericObjectPool.Config;import redis.clients.util.Pool;publicclassJedisPoolextendsPool<Jedis> {public JedisPool(final Config poolConfig, final String host) {        this(poolConfig, host, Protocol.DEFAULT_PORT, Protocol.DEFAULT_TIMEOUT, null, Protocol.DEFAULT_DATABASE);    }    public JedisPool(String host, int port) {        this(new Config(), host, port, Protocol.DEFAULT_TIMEOUT, null, Protocol.DEFAULT_DATABASE);    }    public JedisPool(final String host) {        this(host, Protocol.DEFAULT_PORT);    }    public JedisPool(final Config poolConfig, final String host, int port,            int timeout, final String password) {        this(poolConfig, host, port, timeout, password, Protocol.DEFAULT_DATABASE);    }    public JedisPool(final Config poolConfig, final String host, finalint port) {        this(poolConfig, host, port, Protocol.DEFAULT_TIMEOUT, null, Protocol.DEFAULT_DATABASE);    }    public JedisPool(final Config poolConfig, final String host, finalint port, finalint timeout) {        this(poolConfig, host, port, timeout, null, Protocol.DEFAULT_DATABASE);    }    public JedisPool(final Config poolConfig, final String host, int port, int timeout, final String password,                     finalint database) {        super(poolConfig, new JedisFactory(host, port, timeout, password, database));    }    publicvoid returnBrokenResource(final BinaryJedis resource) {        returnBrokenResourceObject(resource);    }    publicvoid returnResource(final BinaryJedis resource) {        returnResourceObject(resource);    }    /**     * PoolableObjectFactory custom impl.     */privatestaticclassJedisFactoryextendsBasePoolableObjectFactory {privatefinal String host;        privatefinalint port;        privatefinalint timeout;        privatefinal String password;        privatefinalint database;        public JedisFactory(final String host, finalint port,                finalint timeout, final String password, finalint database) {            super();            this.host = host;            this.port = port;            this.timeout = timeout;            this.password = password;            this.database = database;        }        public Object makeObject() throws Exception {            final Jedis jedis = new Jedis(this.host, this.port, this.timeout);            jedis.connect();            if (null != this.password) {                jedis.auth(this.password);            }            if( database != 0 ) {                jedis.select(database);            }            return jedis;        }        publicvoid destroyObject(final Object obj) throws Exception {            if (obj instanceof Jedis) {                final Jedis jedis = (Jedis) obj;                if (jedis.isConnected()) {                    try {                        try {                            jedis.quit();                        } catch (Exception e) {                        }                        jedis.disconnect();                    } catch (Exception e) {                    }                }            }        }        publicboolean validateObject(final Object obj) {            if (obj instanceof Jedis) {                final Jedis jedis = (Jedis) obj;                try {                    return jedis.isConnected();/* && jedis.ping().equals("PONG");*/                } catch (final Exception e) {                    returnfalse;                }            } else {                returnfalse;            }        }    }}

其中JedisFactory繼承自BasePoolableObjectFactory,只實現了3個方法

makeObject(),串連,new Socket()

destroyObject()--中斷連線,

validateObject()--ping


 

 

 

 

Pool原始碼

package redis.clients.util;import org.apache.commons.pool.PoolableObjectFactory;import org.apache.commons.pool.impl.GenericObjectPool;import redis.clients.jedis.exceptions.JedisConnectionException;import redis.clients.jedis.exceptions.JedisException;publicabstractclassPool<T> {privatefinal GenericObjectPool internalPool;    public Pool(final GenericObjectPool.Config poolConfig,            PoolableObjectFactory factory) {        this.internalPool = new GenericObjectPool(factory, poolConfig);    }    @SuppressWarnings("unchecked")    public T getResource() {        try {            return (T) internalPool.borrowObject();        } catch (Exception e) {            thrownew JedisConnectionException(                    "Could not get a resource from the pool", e);        }    }    publicvoid returnResourceObject(final Object resource) {        try {            internalPool.returnObject(resource);        } catch (Exception e) {            thrownew JedisException(                    "Could not return the resource to the pool", e);        }    }    publicvoid returnBrokenResource(final T resource) {        returnBrokenResourceObject(resource);    }    publicvoid returnResource(final T resource) {        returnResourceObject(resource);    }    protectedvoid returnBrokenResourceObject(final Object resource) {        try {            //失效            internalPool.invalidateObject(resource);        } catch (Exception e) {            thrownew JedisException(                    "Could not return the resource to the pool", e);        }    }    publicvoid destroy() {        try {            internalPool.close();        } catch (Exception e) {            thrownew JedisException("Could not destroy the pool", e);        }    }}

JedisPoolConfig原始碼

publicclassJedisPoolConfigextendsConfig {public JedisPoolConfig() {        // defaults to make your life with connection pool easier :)        setTestWhileIdle(true);        setMinEvictableIdleTimeMillis(60000);        setTimeBetweenEvictionRunsMillis(30000);        setNumTestsPerEvictionRun(-1);    }    publicint getMaxIdle() {        return maxIdle;    }    publicvoid setMaxIdle(int maxIdle) {        this.maxIdle = maxIdle;    }    publicint getMinIdle() {        return minIdle;    }    publicvoid setMinIdle(int minIdle) {        this.minIdle = minIdle;    }    publicint getMaxActive() {        return maxActive;    }    publicvoid setMaxActive(int maxActive) {        this.maxActive = maxActive;    }    publiclong getMaxWait() {        return maxWait;    }    publicvoid setMaxWait(long maxWait) {        this.maxWait = maxWait;    }    publicbyte getWhenExhaustedAction() {        return whenExhaustedAction;    }    publicvoid setWhenExhaustedAction(byte whenExhaustedAction) {        this.whenExhaustedAction = whenExhaustedAction;    }    publicboolean isTestOnBorrow() {        return testOnBorrow;    }    publicvoid setTestOnBorrow(boolean testOnBorrow) {        this.testOnBorrow = testOnBorrow;    }    publicboolean isTestOnReturn() {        return testOnReturn;    }    publicvoid setTestOnReturn(boolean testOnReturn) {        this.testOnReturn = testOnReturn;    }    publicboolean isTestWhileIdle() {        return testWhileIdle;    }    publicvoid setTestWhileIdle(boolean testWhileIdle) {        this.testWhileIdle = testWhileIdle;    }    publiclong getTimeBetweenEvictionRunsMillis() {        return timeBetweenEvictionRunsMillis;    }    publicvoid setTimeBetweenEvictionRunsMillis(            long timeBetweenEvictionRunsMillis) {        this.timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis;    }    publicint getNumTestsPerEvictionRun() {        return numTestsPerEvictionRun;    }    publicvoid setNumTestsPerEvictionRun(int numTestsPerEvictionRun) {        this.numTestsPerEvictionRun = numTestsPerEvictionRun;    }    publiclong getMinEvictableIdleTimeMillis() {        return minEvictableIdleTimeMillis;    }    publicvoid setMinEvictableIdleTimeMillis(long minEvictableIdleTimeMillis) {        this.minEvictableIdleTimeMillis = minEvictableIdleTimeMillis;    }    publiclong getSoftMinEvictableIdleTimeMillis() {        return softMinEvictableIdleTimeMillis;    }    publicvoid setSoftMinEvictableIdleTimeMillis(            long softMinEvictableIdleTimeMillis) {        this.softMinEvictableIdleTimeMillis = softMinEvictableIdleTimeMillis;    }}

 

JedisPool使用原理和原始碼

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.