gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 11:31:00 27 4
gpt4 key购买 nike

我正在使用适用于 Windows 的 Redis(3.2.100) 在 Java 中缓存我的数据库数据。这是我的 redis 初始化代码:

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);
}
}

这是缓存代码:

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方法抛出:

redis.clients.jedis.exceptions.JedisException: Could not get a resource from the pool

那么如何重用连接或关闭连接。我正在使用这个命令来发现客户端已达到最大值。

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

如何解决?

最佳答案

记得关闭redis连接,修改这个函数如下:

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;
}

关于java - 如何在 Java 中重用 redis(JRedis) 连接池,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40414013/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com