首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >java jedis (redis)无法连接

java jedis (redis)无法连接
EN

Stack Overflow用户
提问于 2017-09-04 10:17:32
回答 1查看 988关注 0票数 2

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

下面是我的RedisDatabase类:

代码语言:javascript
复制
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;
    }

}

下面是我的错误:

代码语言:javascript
复制
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
EN

回答 1

Stack Overflow用户

发布于 2017-09-04 21:54:43

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

删除块内对jedis.close的调用,只使用try-with-resource功能。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46029493

复制
相关文章

相似问题

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