关于配置Java redis 连接池报错的问题

俊俏的俊 发表于: 2021-02-27   最后更新时间: 2021-03-01 14:02:15   1,295 游览

有一个高频繁查询redis数据的接口 用java 给redis配置连接池 运行一段时间后,就会报Could not get a resource from the pool,redis查询接口调用非常频繁 每运行了一段时间后就会报错 请教大佬这是什么原因

nested exception is redis.clients.jedis.exceptions.JedisException: Could not get a resource from the pool] with root cause
java.util.NoSuchElementException: Timeout waiting for idle object

Java连接池的配置

public class RedisPoolUtil {
    private static JedisPool pool = null;
    /**
     * 获取jedis连接池
     * */
    public static JedisPool getPool()
    {
        if(pool == null)
        {
            //创建jedis连接池配置
            JedisPoolConfig config = new JedisPoolConfig();
            //最大连接数
            config.setMaxTotal(900);
            config.setMaxWaitMillis(3000);
            config.setTestOnBorrow(true);
            //最大空闲连接
            config.setMaxIdle(50);
            //创建redis连接池
            pool = new JedisPool(config,"127.0.0.1",26379,3000,"******",10);
        }
        return pool;
    }
    /**
     * 获取jedis连接
     * */
    public static Jedis getConn()
    {
        return getPool().getResource();
    }

}

Java取redis数据的接口

    public JSONObject queryRedisByKey(Integer flag, String key, Integer db) {
        Jedis jedis = RedisPoolUtil.getConn();
        JSONObject json = new JSONObject();
        switch (flag){
            case 1: //String
                //判断是否存在key 存在查询返回 不存在返回失败
                if (jedis.exists(key)) {
                    try {
                        String obj = jedis.get(key);
                        json.put("status", 0);
                        json.put("msg", "查询成功");
                        json.put("data", obj);
                        return Gsons.data(json);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    finally {
                        if (jedis != null)
                            jedis.close();
                    }
                } else {
                    json.put("status", 1);
                    json.put("msg", "查询失败");
                    return Gsons.data(json);
                }
                break;
                }
                }

已经尝试过把setMaxTotalsetTestOnBorrow加上了,仍然没有解决问题。

请大佬帮忙看下哪里的问题,非常感谢。

发表于 2021-02-27
添加评论

简单读了一下,你的

jedis.close();

如果条件为else的时候,没有关闭。

俊俏的俊 -> 半兽人 3年前

非常感谢 这个问题 已经发现了 改掉了 但是还是报这个错误 没有找到原因,可以给分析一下吗谢谢了

半兽人 -> 俊俏的俊 3年前

1、把JedisPool升到最新的版本(听说老版本有bug)
2、代码依然不严谨,try包裹业务,保障无论什么业务都释放jedis。

Jedis jedis = RedisPoolUtil.getConn();
JSONObject json = new JSONObject();
try{
    switch (flag)
    ...
} catch (Exception e) {
    e.printStackTrace();
}
finally {
    if (jedis != null)
        jedis.close();
}
俊俏的俊 -> 半兽人 3年前

嗯 感谢大佬

你的答案

查看redis相关的其他问题或提一个您自己的问题