`
zx246212
  • 浏览: 1086 次
  • 性别: Icon_minigender_1
  • 来自: 常州
社区版块
存档分类
最新评论

jedispool使用中的问题

阅读更多

最近在使用redis连接池的时候出现很多问题,现在记下来,也给正在研究的同仁们一点建议;

我使用的是redis-2.4.18,连接池使用的是JedisPool;

在使用过程中,发现redis报各种异常,socket closed,类型转换异常,Could not get a resource from the pool等等;总之没有消停过。

经过一个多星期的整理,发现主要是以下原因导致了这些异常:
1.redis连接池的回收机制;
  这应该算是jedis的异常,使用完redis之后,必须将连接进行合理的回收。
  回收分为2种:
           1.正常回收  

                   returnResource

           2.异常回收

                   returnBrokenResource
  回收代码如下:

                                                Jedis redisWhile = null;
						try{
							redisWhile = RedisFactory.newRedis();
							//redis操作
						}catch(Exception ex){
							if(redisWhile!=null){
								RedisFactory.returnDestoryRedis(redisWhile);
							}
							ex.printStackTrace();
						}finally{
							RedisFactory.returnRedisPool(redisWhile);
						}
  

 每一次使用redis都要try catch;

2.redis的连接不能跨线程

  这个当时坑了我很久,一个方法中如果使用了redis连接,那么在收回这个连接之前,代码中不能请求其他的redis连接;

 

   Jedis redisWhile = null;
						try{
							redisWhile = RedisFactory.newRedis();
							test();           //如果这个方法中也包含了redis连接池的请求,那么你悲催了
						}catch(Exception ex){
							if(redisWhile!=null){
								RedisFactory.returnDestoryRedis(redisWhile);
							}
							ex.printStackTrace();
						}finally{
							RedisFactory.returnRedisPool(redisWhile);
						}

 

 如果保持这两点,那么调试下来应该能解决很多异常了。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics