zoukankan      html  css  js  c++  java
  • redis运用连接池报错解决

    redis使用连接池报错解决
    redis使用十几小时就一直报异常

    redis.clients.jedis.exceptions.JedisConnectionException: Could not get a resource from the pool  
        at redis.clients.util.Pool.getResource(Pool.java:22)  
        at com.derbysoft.jredis.longkeytest.BorrowObject.run(BorrowObject.java:22)  
        at java.lang.Thread.run(Thread.java:662)  
    Caused by: java.util.NoSuchElementException: Timeout waiting for idle object  
        at org.apache.commons.pool.impl.GenericObjectPool.borrowObject(GenericObjectPool.java:1134)  
        at redis.clients.util.Pool.getResource(Pool.java:20)  

    原因是没有回收资源导致
    正确的做法是

    ShardedJedis jedis = shardedJedisPool.getResource();
    try {
        jedis.set(key, value);
    } finally {
        shardedJedisPool.returnResource(jedis);
    }

    更新内容:

    如果你用的jedis 2.4.2以及以前版本,用完之后别忘了return连接到资源池。

    不过2.5.0版本之后,jedis使用了try-with-resource,jedis用完了就会自动归还了,不用每次都自己return了。

    各种链接数的参数自己调一下。例如MaxTotal,MaxIdle等等~

    如果redis server不在局域网内,可能会因为network问题导致链接超时,会抛出socket的异常,当然写数据就也会丢失。

    connection的timeout默认是2000ms,你可以自己调的大一些,这样网络慢的时候就不至于丢失数据。

    十分重要的一点:在开发的时候,方法A调用方法B,方法A需要获取jedis 链接,方法B也要获取jedis链接,在实现的时候尽量让他们公用连接,例如B用A的链接,这样效率会快非常多,而且也不会浪费链接。

    最重要的一点,从google老外回答:

    1.I test it using a multi-thread code, when the poolSize > maxclients(redis.conf),
    it will throw this exception. And it runs well when the maxclients is larger than poolSize.


    2.If you set maxclients to 10, and set fixed thread pool size to 20, it prints ".. fail to get connection...".
    If you set maxclients to 10, and set fixed thread pool size to 5, it runs well.

    从而得之,在redis配置文件,redis.conf文件中,有个参数设置,maxclients(默认是注释掉的,不设置此值时表示无redis客户端连接个数限制)。

    设置时,maxclients的值要大于poolSize(最大连接池的链接个数)。

  • 相关阅读:
    大数据量问题,按需按实际查询而不是一次加载。
    spring中注解事务认识
    sqlmap文件在tomcat7中运行报错原因及<![CDATA[ ]]>
    网站404,500错误页面的处理,及500异常写入errorLog日志
    javascript div z-index, input tabindex属性说明
    sqlmap映射继承机制及映射字段顺序与SQL查询字段顺序无关
    jquery类选择器无法取得对象问题原因
    linux服务器初步印象,远程连接mysql数据库,传输文件,启动/关闭tomcat命令
    Linux iptables 防火墙详解
    Nginx之location 匹配规则详解
  • 原文地址:https://www.cnblogs.com/gisblogs/p/4076285.html
Copyright © 2011-2022 走看看