返回到文章

采纳

编辑于 4年前

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

redis

有一个高频繁查询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加上了,仍然没有解决问题。

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