jedispool 连 redis 高并发卡死

java端在使用jedispool 连接redis的时候,在高并发的时候经常死锁,或报连接异常,JedisConnectionException,或者getResource 异常等各种问题

在使用jedispool 的时候一定要注意两点

1。 在获取 jedisPool和jedis的时候加上线程同步,保证不要创建过多的jedispool 和 jedis

2。 用完Jedis实例后需要返还给JedisPool

整理了一下redis工具类,通过大量测试和高并发测试的

  1. package com.caspar.util;  
  2.   
  3. import java.util.concurrent.locks.ReentrantLock;  
  4.   
  5. import org.apache.log4j.Logger;  
  6. import redis.clients.jedis.Jedis;  
  7. import redis.clients.jedis.JedisPool;  
  8. import redis.clients.jedis.JedisPoolConfig;  
  9.   
  10. /** 
  11.  * Redis 工具类 
  12.  * @author caspar 
  13.  * 
  14.  */  
  15. public class RedisUtil {  
  16.       
  17.     protected static ReentrantLock lockPool = new ReentrantLock();  
  18.     protected static ReentrantLock lockJedis = new ReentrantLock();  
  19.       
  20.     protected static Logger logger = Logger.getLogger(RedisUtil.class);  
  21.       
  22.     //Redis服务器IP  
  23.     private static String ADDR_ARRAY = FileUtil.getPropertyValue("/properties/redis.properties""server");  
  24.       
  25.     //Redis的端口号  
  26.     private static int PORT = FileUtil.getPropertyValueInt("/properties/redis.properties""port");  
  27.       
  28.     //访问密码  
  29. //    private static String AUTH = FileUtil.getPropertyValue("/properties/redis.properties", "auth");  
  30.       
  31.     //可用连接实例的最大数目,默认值为8;  
  32.     //如果赋值为-1,则表示不限制;如果pool已经分配了maxActive个jedis实例,则此时pool的状态为exhausted(耗尽)。  
  33.     private static int MAX_ACTIVE = FileUtil.getPropertyValueInt("/properties/redis.properties""max_active");;  
  34.       
  35.     //控制一个pool最多有多少个状态为idle(空闲的)的jedis实例,默认值也是8。  
  36.     private static int MAX_IDLE = FileUtil.getPropertyValueInt("/properties/redis.properties""max_idle");;  
  37.       
  38.     //等待可用连接的最大时间,单位毫秒,默认值为-1,表示永不超时。如果超过等待时间,则直接抛出JedisConnectionException;  
  39.     private static int MAX_WAIT = FileUtil.getPropertyValueInt("/properties/redis.properties""max_wait");;  
  40.   
  41.     //超时时间  
  42.     private static int TIMEOUT = FileUtil.getPropertyValueInt("/properties/redis.properties""timeout");;  
  43.       
  44.     //在borrow一个jedis实例时,是否提前进行validate操作;如果为true,则得到的jedis实例均是可用的;  
  45.     private static boolean TEST_ON_BORROW = FileUtil.getPropertyValueBoolean("/properties/redis.properties""test_on_borrow");;  
  46.       
  47.     private static JedisPool jedisPool = null;  
  48.       
  49.     /** 
  50.      * redis过期时间,以秒为单位 
  51.      */  
  52.     public final static int EXRP_HOUR = 60*60;          //一小时  
  53.     public final static int EXRP_DAY = 60*60*24;        //一天  
  54.     public final static int EXRP_MONTH = 60*60*24*30;   //一个月  
  55.       
  56.     /** 
  57.      * 初始化Redis连接池 
  58.      */  
  59.     private static void initialPool(){  
  60.         try {  
  61.             JedisPoolConfig config = new JedisPoolConfig();  
  62.             config.setMaxTotal(MAX_ACTIVE);  
  63.             config.setMaxIdle(MAX_IDLE);  
  64.             config.setMaxWaitMillis(MAX_WAIT);  
  65.             config.setTestOnBorrow(TEST_ON_BORROW);  
  66.             jedisPool = new JedisPool(config, ADDR_ARRAY.split(",")[0], PORT, TIMEOUT);  
  67.         } catch (Exception e) {  
  68.             logger.error("First create JedisPool error : "+e);  
  69.             try{  
  70.                 //如果第一个IP异常,则访问第二个IP  
  71.                 JedisPoolConfig config = new JedisPoolConfig();  
  72.                 config.setMaxTotal(MAX_ACTIVE);  
  73.                 config.setMaxIdle(MAX_IDLE);  
  74.                 config.setMaxWaitMillis(MAX_WAIT);  
  75.                 config.setTestOnBorrow(TEST_ON_BORROW);  
  76.                 jedisPool = new JedisPool(config, ADDR_ARRAY.split(",")[1], PORT, TIMEOUT);  
  77.             }catch(Exception e2){  
  78.                 logger.error("Second create JedisPool error : "+e2);  
  79.             }  
  80.         }  
  81.     }  
  82.       
  83.       
  84.     /** 
  85.      * 在多线程环境同步初始化 
  86.      */  
  87.     private static void poolInit() {  
  88.         //断言 ,当前锁是否已经锁住,如果锁住了,就啥也不干,没锁的话就执行下面步骤  
  89.         assert ! lockPool.isHeldByCurrentThread();    
  90.         lockPool.lock();  
  91.         try {    
  92.             if (jedisPool == null) {    
  93.                 initialPool();  
  94.             }  
  95.         }catch(Exception e){  
  96.             e.printStackTrace();  
  97.         } finally {    
  98.             lockPool.unlock();  
  99.         }  
  100.     }  
  101.       
  102.       
  103.     public static Jedis getJedis() {  
  104.         //断言 ,当前锁是否已经锁住,如果锁住了,就啥也不干,没锁的话就执行下面步骤  
  105.         assert ! lockJedis.isHeldByCurrentThread();    
  106.         lockJedis.lock();  
  107.           
  108.         if (jedisPool == null) {    
  109.             poolInit();  
  110.         }  
  111.         Jedis jedis = null;  
  112.         try {    
  113.             if (jedisPool != null) {    
  114.                 jedis = jedisPool.getResource();   
  115.             }  
  116.         } catch (Exception e) {    
  117.             logger.error("Get jedis error : "+e);  
  118.         }finally{  
  119.             returnResource(jedis);  
  120.             lockJedis.unlock();  
  121.         }  
  122.         return jedis;  
  123.     }    
  124.       
  125.       
  126.     /** 
  127.      * 释放jedis资源 
  128.      * @param jedis 
  129.      */  
  130.     public static void returnResource(final Jedis jedis) {  
  131.         if (jedis != null && jedisPool !=null) {  
  132.             jedisPool.returnResource(jedis);  
  133.         }  
  134.     }  
  135.       
  136.       
  137.     /** 
  138.      * 设置 String 
  139.      * @param key 
  140.      * @param value 
  141.      */  
  142.     public synchronized static void setString(String key ,String value){  
  143.         try {  
  144.             value = StringUtil.isEmpty(value) ? "" : value;  
  145.             getJedis().set(key,value);  
  146.         } catch (Exception e) {  
  147.             logger.error("Set key error : "+e);  
  148.         }  
  149.     }  
  150.       
  151.     /** 
  152.      * 设置 过期时间 
  153.      * @param key 
  154.      * @param seconds 以秒为单位 
  155.      * @param value 
  156.      */  
  157.     public synchronized static void setString(String key ,int seconds,String value){  
  158.         try {  
  159.             value = StringUtil.isEmpty(value) ? "" : value;  
  160.             getJedis().setex(key, seconds, value);  
  161.         } catch (Exception e) {  
  162.             logger.error("Set keyex error : "+e);  
  163.         }  
  164.     }  
  165.       
  166.     /** 
  167.      * 获取String值 
  168.      * @param key 
  169.      * @return value 
  170.      */  
  171.     public synchronized static String getString(String key){  
  172.         if(getJedis() == null || !getJedis().exists(key)){  
  173.             return null;  
  174.         }  
  175.         return getJedis().get(key);  
  176.     }  
  177.       

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值