Jedispool use principle and source code

Source: Internet
Author: User

Use of 1,jedispool
<!--Connection Pool configuration information--<beanid= "Jedisconfig" class= "Redis.clients.jedis.JedisPoolConfig" ><!--shows how many Jedis instances a pool can have --<propertyname= "Maxactive" value= "ten"/><!--Max Idle--><propertyname= "Maxidle" value= "5"/><!--min .<propertyname= "Minidle" value= "1"/>< Whether to check connectivity availability (ping ()) When a Jedis instance is obtained --<propertyname= "Testonborrow" value= "true"/><!--return a Jedis instance to the pool, check connectivity availability (ping ()) --<propertyname= "Testonreturn" value= "true"/><!--idle condition monitoring is checked with asynchronous thread evict,<propertyname= "Testwhileidle" value= "true"/><!--The number of Jedis instances in a pool of up to evict<propertyname= "Numtestsperevictionrun" value= "ten"/><!--test idle thread-time interval-<propertyname= "Timebetweenevictionrunsmillis" value= "60000"/><!--maximum wait time --<propertyname= "maxwait" value= "/><propertyname=" whenexhaustedaction "value=" "/>//WHEN_EXHAUSTED _fail = 0;    Throw the exception directly throw new Nosuchelementexception ("Pool exhausted"); When_exhausted_block = 1;borrowobject () will block until a new or idle object is available, or if MAXWAIT is configured,//If the request blocking timeout is    Throws Nosuchelementexception. If the maxwait is negative, the request will have no limit to the resistance//plug down, the default configuration. When_exhausted_grow = 2;borrowobject () will continue to create a new object and return, so the number of images maintained by the pool will exceed maxactive;//&LT;/BEAN&G T
 
 
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);        }    }}

Get Jedis

pool.getResource();

The GetResource method that can directly see the pool,

Eventually, it's genericobjectpool. borrowobject () method borrowing objects

@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);    }}

When the return is exhausted, the Genericobjectpool returnobject () method is called.

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);}}

Error, calling the Invalidateobject () method of the Genericobjectpool

Finally, call Jedis.quit () in Jedisfactory's Destroyobject () request server to close the connection

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 Source Code

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, PROTOC Ol.    Default_timeout, NULL, protocol.default_database); Public Jedispool (String host, int. port) {This (new Config (), host, port, protocol.default_timeout, NULL, Proto Col.    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, Pro Tocol.    Default_timeout, NULL, protocol.default_database); } public Jedispool (final Config poolconfig, final String host, Finalint port, finalint timeout) {This (poolconfi    G, 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 dat            Abase) {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 Vali                Dateobject (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; }        }    }}

Where Jedisfactory inherits from Basepoolableobjectfactory, only 3 methods are implemented

Makeobject (), Connection, new Socket ()

Destroyobject ()--Disconnect,

Validateobject ()--ping

Pool Source Code

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.internalpoo    L = new Genericobjectpool (factory, Poolconfig); } @SuppressWarnings ("Unchecked") public T getresource () {try {return (T) internalpool.borrowobje        CT (); } catch (Exception e) {thrownew jedisconnectionexception ("Could not get a resource from th        E Pool ", e); }} publicvoid returnresourceobject (final Object Resource) {try {internalpool.returnobject (Resou        RCE); } 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 {             //FailureInternalpool.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 Source Code

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.timebetween    Evictionrunsmillis = Timebetweenevictionrunsmillis;    } publicint Getnumtestsperevictionrun () {return numtestsperevictionrun; } publicvoid setnumtestsperevictionrun (int numtestsperevictionrun) {This.numtestsperevictionrun = NumTestsPerEv    Ictionrun; } Publiclong Getminevictableidletimemillis () {return minevictaBleidletimemillis; } publicvoid Setminevictableidletimemillis (Long minevictableidletimemillis) {This.minevictableidletimemillis =    Minevictableidletimemillis;    } Publiclong Getsoftminevictableidletimemillis () {return softminevictableidletimemillis; } publicvoid Setsoftminevictableidletimemillis (Long softminevictableidletimemillis) {This.softminev    Ictableidletimemillis = Softminevictableidletimemillis; }}

 

Jedispool use principle and source code

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.