首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在Java中重用redis(JRedis)池连接

如何在Java中重用redis(JRedis)池连接
EN

Stack Overflow用户
提问于 2016-11-04 01:38:54
回答 1查看 1.9K关注 0票数 0

我使用Redis(3.2.100) for Java.This缓存我的数据库数据,这是我的redis init代码:

代码语言:javascript
复制
private static Dictionary<Integer, JedisPool> pools = new Hashtable();

    static {
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxIdle(2);
        config.setMaxTotal(10);
        config.setTestOnBorrow(true);
        config.setMaxWaitMillis(2000);
        for (int i = 0; i < 16; i++) {
            JedisPool item  = new JedisPool(config, "127.0.0.1", 6379,10*1000);
            pools.put(i, item);
        }
    }

这是缓存代码:

代码语言:javascript
复制
public static String get(String key, Integer db) {
        JedisPool poolItem = pools.get(db);
        Jedis jredis = poolItem.getResource();
        String result = jredis.get(key);
        return result;
    }

问题是当程序运行一段时间后,getResource方法抛出:

代码语言:javascript
复制
redis.clients.jedis.exceptions.JedisException: Could not get a resource from the pool

因此,如何重用连接或关闭连接,我正在使用此命令来查找客户端已达到最大值。

代码语言:javascript
复制
D:\Program Files\Redis>redis-cli.exe info clients
# Clients
connected_clients:11
client_longest_output_list:0
client_biggest_input_buf:0
blocked_clients:0

怎么修呢?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-11-05 08:57:32

请记住关闭redis连接,如下所示修改此函数:

代码语言:javascript
复制
public static String get(String key, Integer db) {
        JedisPool poolItem = pools.get(db);
        Jedis jredis = null;
        String result = null;
        try {
            jredis = poolItem.getResource();
            result = jredis.get(key);
        } catch (Exception e) {
            log.error("get value error", e);
        } finally {
            if (jredis != null) {
                jredis.close();
            }
        }
        return result;
    }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40414013

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档