Java的Redis连接池代码性能不错
生活随笔
收集整理的這篇文章主要介紹了
Java的Redis连接池代码性能不错
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
其實這個是引用自網友http://blog.csdn.net/tuposky/article/details/45340183,有2個版本,差別就是ReentrantLock和synchronized。另外原作者使用了斷言,我覺得這個還是不用為好。
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 工具類*/
public class JedisUtil {protected static ReentrantLock lockPool = new ReentrantLock();protected static ReentrantLock lockJedis = new ReentrantLock();protected static Logger logger = Logger.getLogger(JedisUtil.class);//Redis服務器IPprivate static String ADDR_ARRAY = "xxx.xxx.xxx.xxx";//Redis的端口號private static int PORT = 6379;//訪問密碼private static String AUTH = "http://blog.csdn.net/unix21";//可用連接實例的最大數目,默認值為8;//如果賦值為-1,則表示不限制;如果pool已經分配了maxActive個jedis實例,則此時pool的狀態為exhausted(耗盡)。private static int MAX_ACTIVE = 8;//控制一個pool最多有多少個狀態為idle(空閑的)的jedis實例,默認值也是8。private static int MAX_IDLE = 8;//等待可用連接的最大時間,單位毫秒,默認值為-1,表示永不超時。如果超過等待時間,則直接拋出JedisConnectionException;private static int MAX_WAIT = 3000;//超時時間private static int TIMEOUT = 10000;//在borrow一個jedis實例時,是否提前進行validate操作;如果為true,則得到的jedis實例均是可用的;private static boolean TEST_ON_BORROW = false;private static JedisPool jedisPool = null;/*** redis過期時間,以秒為單位*/public final static int EXRP_HOUR = 60 * 60; //一小時public final static int EXRP_DAY = 60 * 60 * 24; //一天public final static int EXRP_MONTH = 60 * 60 * 24 * 30; //一個月/*** 初始化Redis連接池*/private 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 {//如果第一個IP異常,則訪問第二個IPJedisPoolConfig 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);}}}/*** 在多線程環境同步初始化*/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;}/*** 釋放jedis資源** @param jedis*/public static void returnResource(final Jedis jedis) {if (jedis != null && jedisPool != null) {jedisPool.returnResource(jedis);}}/*** 設置 String** @param key* @param value*/public synchronized static void setString(String key, String value) {try {value = StringUtils.isEmpty(value) ? "" : value;getJedis().set(key, value);} catch (Exception e) {logger.error("Set key error : " + e);}}/*** 設置 過期時間** @param key* @param seconds 以秒為單位* @param value*/public synchronized 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);}}/*** 獲取String值** @param key* @return value*/public synchronized static String getString(String key) {if (getJedis() == null || !getJedis().exists(key)) {return null;}return getJedis().get(key);}
}
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 工具類*/
public class JedisUtil {protected static ReentrantLock lockPool = new ReentrantLock();protected static ReentrantLock lockJedis = new ReentrantLock();protected static Logger logger = Logger.getLogger(JedisUtil.class);//Redis服務器IPprivate static String ADDR_ARRAY = "xxx.xxx.xxx.xxx";//Redis的端口號private static int PORT = 6379;//訪問密碼private static String AUTH = "http://blog.csdn.net/unix21";//可用連接實例的最大數目,默認值為8;//如果賦值為-1,則表示不限制;如果pool已經分配了maxActive個jedis實例,則此時pool的狀態為exhausted(耗盡)。private static int MAX_ACTIVE = 8;//控制一個pool最多有多少個狀態為idle(空閑的)的jedis實例,默認值也是8。private static int MAX_IDLE = 8;//等待可用連接的最大時間,單位毫秒,默認值為-1,表示永不超時。如果超過等待時間,則直接拋出JedisConnectionException;private static int MAX_WAIT = 3000;//超時時間private static int TIMEOUT = 10000;//在borrow一個jedis實例時,是否提前進行validate操作;如果為true,則得到的jedis實例均是可用的;private static boolean TEST_ON_BORROW = false;private static JedisPool jedisPool = null;/*** redis過期時間,以秒為單位*/public final static int EXRP_HOUR = 60 * 60; //一小時public final static int EXRP_DAY = 60 * 60 * 24; //一天public final static int EXRP_MONTH = 60 * 60 * 24 * 30; //一個月/*** 初始化Redis連接池*/private 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 {//如果第一個IP異常,則訪問第二個IPJedisPoolConfig 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);}}}/*** 在多線程環境同步初始化*/private static synchronized void poolInit() {if (jedisPool == null) { initialPool();}}/*** 同步獲取Jedis實例* @return Jedis*/public synchronized static Jedis getJedis() { 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);}return jedis;} /*** 釋放jedis資源** @param jedis*/public static void returnResource(final Jedis jedis) {if (jedis != null && jedisPool != null) {jedisPool.returnResource(jedis);}}/*** 設置 String** @param key* @param value*/public synchronized static void setString(String key, String value) {try {value = StringUtils.isEmpty(value) ? "" : value;getJedis().set(key, value);} catch (Exception e) {logger.error("Set key error : " + e);}}/*** 設置 過期時間** @param key* @param seconds 以秒為單位* @param value*/public synchronized 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);}}/*** 獲取String值** @param key* @return value*/public synchronized static String getString(String key) {if (getJedis() == null || !getJedis().exists(key)) {return null;}return getJedis().get(key);}
}
多線程
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("【輸出>>>>】foo:" + foo + " 第:"+i+"個線程" +"當前時間:"+DateUtil.getNowTimeString());}
}
起10000個線程
public static void main(String[] args) { for (int i = 0; i < 10000; i++) { ClientThread t = new ClientThread(i);t.start();}}
運行非常穩定:
在單機4核普通PC機器測試下來10000條數據跑了2秒,性能還是不錯的,沒有報異常。
下面是一個處理不好的情況,就會報出種種異常,這種連接池一定要用多線程測試,不然線下沒事,線上就會時不時的出問題:
總結
以上是生活随笔為你收集整理的Java的Redis连接池代码性能不错的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 匿名函数应用-多线程测试代码
- 下一篇: junit集成Hamcrest测试集合中