JedisException: Could not get a resource from the pool
项目中使用jedis客户端操作redis
<dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.9.0</version> </dependency>
代码没有变更,换个环境本地运行异常:
redis.clients.jedis.exceptions.JedisException: Could not get a resource from the pool at redis.clients.util.Pool.getResource(Pool.java:51) at redis.clients.jedis.ShardedJedisPool.getResource(ShardedJedisPool.java:36)
Caused by: java.util.NoSuchElementException: Unable to validate object at org.apache.commons.pool2.impl.GenericObjectPool.borrowObject(GenericObjectPool.java:495) at org.apache.commons.pool2.impl.GenericObjectPool.borrowObject(GenericObjectPool.java:362) at redis.clients.util.Pool.getResource(Pool.java:49)
首先确定网络可通,linux防火墙开放了端口。
然后使用自带的redis-cli.exe连接
提示NOAUTH Authentication required.
明显是设置了密码。
于是查看配置文件找到 requirepass,确定设置了密码。
通过验证密码,客户端使用正常。
顺藤摸瓜找到Jedis的配置 ShardedJedisPool
JedisShardInfo有password属性
此项需要根据实际redis的配置密码的情况设置password,如果拿到的密码为空,则不设置即可。
参考代码:
@Bean public ShardedJedisPool getJedisPool() { JedisPoolConfig jedisPoolConfig = new JedisPoolConfig(); jedisPoolConfig.setMaxIdle(maxIdle); jedisPoolConfig.setMaxTotal(maxTotal); jedisPoolConfig.setMinIdle(minIdle); jedisPoolConfig.setMaxWaitMillis(maxWait); jedisPoolConfig.setTestOnBorrow(true); jedisPoolConfig.setTestOnReturn(true); jedisPoolConfig.setBlockWhenExhausted(false); JedisShardInfo jedisShardInfo = new JedisShardInfo(host, port); if(!ToolUtil.isEmpty(password)){ jedisShardInfo.setPassword(password); } List<JedisShardInfo> list = new LinkedList<JedisShardInfo>(); list.add(jedisShardInfo); return new ShardedJedisPool(jedisPoolConfig, list); }