Jedis 使用问题及解决方案

Posted by jiangydev on December 3, 2017

[TOC]

Jedis Could not get a resource from the pool

问题分析

  1. 检查 Redis 所在服务器的防火墙是否放行 Redis 服务的端口;

  2. Redis pool (连接池)参数设置存在问题;

  3. 编写代码时,使用完资源未释放,导致资源不够用,与 (2) 有关系。

解决方案

  1. 关闭防火墙或放行端口 ( 以 CentOS 7.0 为例 )
    1
    2
    3
    4
    5
    6
    7
    8
    9
    
    # 查看防火墙状态
    systemctl status firewalld
    # 关闭防火墙
    systemctl disable firewalld
    # 暂时关闭防火墙
    systemctl stop firewalld
    # 放行 6379 端口,并使配置生效
    firewall-cmd --zone=public --add-port=6379/tcp --permanent
    firewall-cmd --reload
    

    CentOS 7.0 版本中,防火墙服务为 firewalled。

  2. 调整 Redis pool 的参数 ```xml
1
2
3
4
5
6
7
8
9
10
>`maxActive`: 可用连接实例的最大数目,为负值时没有限制。
>这个属性在 Redis 的新版本中被去除,可以认为是`maxTotal`。

3. 调用资源后需要手动释放
```java
// Jedis 2.9 以上版本使用 close() 方法释放资源
jedisPool.close();
// 以下两种方法是不赞成的(deprecated)
// jedisPool.returnBrokenResource();
// jedisPool.returnResource();