gpt4 book ai didi

java jedis (redis) 无法连接

转载 作者:IT王子 更新时间:2023-10-29 06:06:15 24 4
gpt4 key购买 nike

我正在尝试在我的 Java 应用程序中使用 Jedis 连接到 Redis。我正在实例化一个 JedisPool 对象,当我获得资源时,它会抛出一个异常,说明它无法返回资源。奇怪的是,如果我只是实例化一个 Jedis 对象,它可以毫无问题地连接,并且我可以更改数据。

这是我的 RedisDatabase 类:

package me.joeleoli.proxylink.database;

import me.joeleoli.proxylink.ProxyLink;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

public class RedisDatabase {

private JedisPool pool;

public RedisDatabase(String host, int port, String password) {
ProxyLink.getInstance().getLogger().info("Attempting to establish Redis connection " + host + ":" + port);

this.pool = new JedisPool(host, port);

try (Jedis jedis = this.pool.getResource()) {
if (password != null && !password.equals("")) {
jedis.auth(password);
}

jedis.select(0);
jedis.close();
}
}

public JedisPool getPool() {
return this.pool;
}

}

这是我的错误:

22:16:15 [INFO] [ProxyLink] Attempting to establish Redis connection 127.0.0.1:6379
22:16:15 [WARNING] Exception encountered when loading plugin: ProxyLink
redis.clients.jedis.exceptions.JedisException: Could not return the resource to the pool
at redis.clients.jedis.JedisPool.returnResource(JedisPool.java:106)
at redis.clients.jedis.JedisPool.returnResource(JedisPool.java:12)
at redis.clients.jedis.Jedis.close(Jedis.java:3206)
at me.joeleoli.proxylink.database.RedisDatabase.<init>(RedisDatabase.java:23)
at me.joeleoli.proxylink.ProxyLink.onEnable(ProxyLink.java:71)
at net.md_5.bungee.api.plugin.PluginManager.enablePlugins(PluginManager.java:227)
at net.md_5.bungee.BungeeCord.start(BungeeCord.java:273)
at net.md_5.bungee.BungeeCordLauncher.main(BungeeCordLauncher.java:111)
at net.md_5.bungee.Bootstrap.main(Bootstrap.java:15)
Caused by: redis.clients.jedis.exceptions.JedisException: Could not return the resource to the pool
at redis.clients.util.Pool.returnResourceObject(Pool.java:61)
at redis.clients.jedis.JedisPool.returnResource(JedisPool.java:103)
... 8 more
Caused by: java.lang.IllegalStateException: Object has already been returned to this pool or is invalid
at org.apache.commons.pool2.impl.GenericObjectPool.returnObject(GenericObjectPool.java:551)
at redis.clients.util.Pool.returnResourceObject(Pool.java:59)
... 9 more

最佳答案

您的代码的问题是在 try-with-resource block 中调用了 jedis.close()。 try-with-resource block 会在 block 退出时关闭您的资源。由于您已经关闭了资源,因此在 block 退出之前,您最终调用了两次关闭。

在 block 中删除对 jedis.close 的调用,只使用 try-with-resource 功能。

关于java jedis (redis) 无法连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46029493/

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