Redis Connection Pool code in Java good performance

Source: Internet
Author: User
Tags redis server

In fact, this is quoted from netizens http://blog.csdn.net/tuposky/article/details/45340183, there are 2 versions, the difference is reentrantlock and synchronized. In addition, the original person used the assertion, I think this is still not good.


Version Reentrantlock

Import Java.util.concurrent.locks.reentrantlock;import Org.apache.commons.lang.stringutils;import Org.apache.log4j.logger;import Redis.clients.jedis.jedis;import Redis.clients.jedis.jedispool;import redis.clients.jedis.jedispoolconfig;/** * Redis Tool class */public class Jedisutil {protected static Reentrantlock Lockpool    = new Reentrantlock ();    protected static Reentrantlock Lockjedis = new Reentrantlock ();    protected static Logger Logger = Logger.getlogger (Jedisutil.class);    Redis server IP private static String Addr_array = "xxx.xxx.xxx.xxx";    The port number of the Redis private static int port = 6379;    Access password private static String AUTH = "http://blog.csdn.net/unix21";    The maximum number of available connection instances, the default value is 8, and//If the assignment is 1, it is unrestricted, and if the pool is already assigned a maxactive Jedis instance, the state of the pool is exhausted (exhausted) at this time.    private static int max_active = 8;    Controls the maximum number of Jedis instances in a pool that have an idle (idle) state, and the default value is 8.    private static int max_idle = 8; The maximum time to wait for an available connection, in milliseconds, and the default value is-1, which means that never times out. If the wait time is exceeded, the jedisconnectionexception is thrown directly; private static int MAX_wait = 3000;    Timeout time private static int timeout = 10000;    Whether the validate operation is performed in advance when a Jedis instance is borrow, and if true, the resulting Jedis instance is available; private static Boolean test_on_borrow = false;    private static Jedispool Jedispool = null; /** * Redis expiration, in seconds */public final static int exrp_hour = 60 * 60;//one hour public final static int Exrp_day = 60 * 60 * 24;//Day public final static int exrp_month = 60 * 60 * 24 * 30;//one month/** * Initialize REDIS connection pool */pri            vate static void Initialpool () {try {jedispoolconfig config = new Jedispoolconfig ();            Config.setmaxtotal (max_active);            Config.setmaxidle (Max_idle);            Config.setmaxwaitmillis (max_wait);            Config.settestonborrow (Test_on_borrow);        Jedispool = new Jedispool (config, addr_array.split (",") [0], PORT, TIMEOUT, AUTH);            } catch (Exception e) {logger.error ("first create Jedispool Error:" + E);   try {//If first IP exception, access second IP             Jedispoolconfig config = new Jedispoolconfig ();                Config.setmaxtotal (max_active);                Config.setmaxidle (Max_idle);                Config.setmaxwaitmillis (max_wait);                Config.settestonborrow (Test_on_borrow);            Jedispool = new Jedispool (config, addr_array.split (",") [1], PORT, TIMEOUT, AUTH);            } catch (Exception E2) {logger.error ("Second Create Jedispool Error:" + E2);        }}}/** * Synchronous initialization in multithreaded environment */private static void Poolinit () {lockpool.lock ();            try {if (Jedispool = = null) {Initialpool ();        }} catch (Exception e) {e.printstacktrace ();        } finally {Lockpool.unlock ();        }} public static Jedis Getjedis () {lockjedis.lock ();        if (Jedispool = = null) {poolinit ();        } Jedis Jedis = null;   try {if (Jedispool! = null) {             Jedis = Jedispool.getresource ();        }} catch (Exception e) {logger.error ("Get Jedis Error:" + E);            } finally {Returnresource (Jedis);        Lockjedis.unlock ();    } return Jedis;        /** * Release Jedis resource * * @param Jedis */public static void Returnresource (final Jedis Jedis) {        if (Jedis! = NULL && Jedispool! = null) {Jedispool.returnresource (Jedis); }}/** * Set String * * @param key * @param value */public synchronized static void Setstrin g (String key, String value) {try {value = Stringutils.isempty (value)?            "": value;        Getjedis (). Set (key, value);        } catch (Exception e) {logger.error ("Set key error:" + E); }}/** * Set Expiration time * * @param key * @param seconds in seconds * @param value */Public Synchron ized static void SetString (String key, int secOnds, String value) {try {value = Stringutils.isempty (value)?            "": value;        Getjedis (). Setex (key, seconds, value);        } catch (Exception e) {logger.error ("Set Keyex Error:" + E); }}/** * Get string Value * * @param key * @return Value */public synchronized static string getst        Ring (String key) {if (Getjedis () = null | |!getjedis (). Exists (key)) {return null;    } return Getjedis (). get (key); }}


version Synchronized
Import Java.util.concurrent.locks.reentrantlock;import Org.apache.commons.lang.stringutils;import Org.apache.log4j.logger;import Redis.clients.jedis.jedis;import Redis.clients.jedis.jedispool;import redis.clients.jedis.jedispoolconfig;/** * Redis Tool class */public class Jedisutil {protected static Reentrantlock Lockpool    = new Reentrantlock ();    protected static Reentrantlock Lockjedis = new Reentrantlock ();    protected static Logger Logger = Logger.getlogger (Jedisutil.class);    Redis server IP private static String Addr_array = "xxx.xxx.xxx.xxx";    The port number of the Redis private static int port = 6379;    Access password private static String AUTH = "http://blog.csdn.net/unix21";    The maximum number of available connection instances, the default value is 8, and//If the assignment is 1, it is unrestricted, and if the pool is already assigned a maxactive Jedis instance, the state of the pool is exhausted (exhausted) at this time.    private static int max_active = 8;    Controls the maximum number of Jedis instances in a pool that have an idle (idle) state, and the default value is 8.    private static int max_idle = 8; The maximum time to wait for an available connection, in milliseconds, and the default value is-1, which means that never times out. If the wait time is exceeded, the jedisconnectionexception is thrown directly; private static int MAX_wait = 3000;    Timeout time private static int timeout = 10000;    Whether the validate operation is performed in advance when a Jedis instance is borrow, and if true, the resulting Jedis instance is available; private static Boolean test_on_borrow = false;    private static Jedispool Jedispool = null; /** * Redis expiration, in seconds */public final static int exrp_hour = 60 * 60;//one hour public final static int Exrp_day = 60 * 60 * 24;//Day public final static int exrp_month = 60 * 60 * 24 * 30;//one month/** * Initialize REDIS connection pool */pri            vate static void Initialpool () {try {jedispoolconfig config = new Jedispoolconfig ();            Config.setmaxtotal (max_active);            Config.setmaxidle (Max_idle);            Config.setmaxwaitmillis (max_wait);            Config.settestonborrow (Test_on_borrow);        Jedispool = new Jedispool (config, addr_array.split (",") [0], PORT, TIMEOUT, AUTH);            } catch (Exception e) {logger.error ("first create Jedispool Error:" + E);   try {//If first IP exception, access second IP             Jedispoolconfig config = new Jedispoolconfig ();                Config.setmaxtotal (max_active);                Config.setmaxidle (Max_idle);                Config.setmaxwaitmillis (max_wait);                Config.settestonborrow (Test_on_borrow);            Jedispool = new Jedispool (config, addr_array.split (",") [1], PORT, TIMEOUT, AUTH);            } catch (Exception E2) {logger.error ("Second Create Jedispool Error:" + E2);  }}}/** * Synchronous initialization in multithreaded environment */private static synchronized void Poolinit () {if (Jedispool = = null)        {Initialpool (); }}/** * Synchronize get Jedis instance * @return Jedis */public synchronized static Jedis Getjedis () {i        F (Jedispool = = null) {poolinit ();        } Jedis Jedis = null;             try {if (Jedispool! = null) {Jedis = Jedispool.getresource (); }} catch (Exception e) {logger.error ("GET Jedis error: "+e);        }finally{Returnresource (Jedis);    } return Jedis;        /** * Release Jedis resource * * @param Jedis */public static void Returnresource (final Jedis Jedis) {        if (Jedis! = NULL && Jedispool! = null) {Jedispool.returnresource (Jedis); }}/** * Set String * * @param key * @param value */public synchronized static void Setstrin g (String key, String value) {try {value = Stringutils.isempty (value)?            "": value;        Getjedis (). Set (key, value);        } catch (Exception e) {logger.error ("Set key error:" + E); }}/** * Set Expiration time * * @param key * @param seconds in seconds * @param value */Public Synchron ized static void SetString (string key, int seconds, string value) {try {value = stringutils.isempty (VA Lue)?            "": value;        Getjedis (). Setex (key, seconds, value); } catch (Exception e) {logger.error ("Set Keyex Error:" + E); }}/** * Get string Value * * @param key * @return Value */public synchronized static string getst        Ring (String key) {if (Getjedis () = null | |!getjedis (). Exists (key)) {return null;    } return Getjedis (). get (key); }}


Multithreading

public class Clientthread extends Thread {    int i = 0;    Public clientthread (int i) {        this.i = i;    }    public void Run () {        date date = new Date ();        DateFormat format = new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss");        String time = Format.format (date);        Jedisutil.setstring ("foo", time);        String foo = jedisutil.getstring ("foo");              System.out.println ("" Output >>>> "foo:" + foo + ":" +i+ "Threads" + "Current Time:" +dateutil.getnowtimestring ());}    }

Up to 10,000 threads

public static void Main (string[] args) {for                      (int i = 0; i < 10000; i++) {                      Clientthread t = new Clientthread (i) ;            T.start ();        }    }


Very stable operation:

In a stand-alone 4-core PC machine test down 10,000 data ran for 2 seconds , performance is good, no report abnormal.


The following is a bad situation, will report a variety of anomalies, this connection pool must be tested with multithreading, otherwise the line is OK, the line will occasionally problem:



Redis Connection Pool code in Java good performance

Related Article

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.