尝试使用 JedisPool 中的链式资源

Try with chained resource in JedisPool

我很困惑: 用法:try(Pipeline pipeline = jedisPool.getResource().pipelined()) 它会关闭管道和绝地实例吗?或者只是关闭管道?

我在多线程中使用它,出现如下错误。我很困惑错误是由 JedisPool 中的 运行 异常引起的(由于 try-with-resource 的使用)或因为死锁(因为 JedisPool 在多线程中表现不佳)?

sun.misc.Unsafe.park(Native Method)
java.util.concurrent.locks.LockSupport.park(LockSupport.java:186)
java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.await(AbstractQueuedSynchronizer.java:2043)
org.apache.commons.pool2.impl.LinkedBlockingDeque.takeFirst(LinkedBlockingDeque.java:583)
org.apache.commons.pool2.impl.GenericObjectPool.borrowObject(GenericObjectPool.java:442)
org.apache.commons.pool2.impl.GenericObjectPool.borrowObject(GenericObjectPool.java:363)
redis.clients.util.Pool.getResource(Pool.java:49)
redis.clients.jedis.JedisPool.getResource(JedisPool.java:226)
io.codis.jodis.RoundRobinJedisPool.getResource(RoundRobinJedisPool.java:214)

Try-with-resources 仅关闭变量,在您的情况下 Pipeline pipeline。您可以在文档中阅读更多内容 https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html

您可以通过示例进行检查:

MyResource class:

class MyResource implements AutoCloseable {

    public SubResource getSubResource() {
        return new SubResource();
    }

    @Override
    public void close() throws Exception {
        System.out.println("Resource closed");
    }
}

SubResource class:

class SubResource implements AutoCloseable{
    @Override
    public void close() throws Exception {
        System.out.println("SubResource closed");
    }
}

Main class:

class Main {

    public static void main(String[] args) {
        try (SubResource s = new MyResource().getSubResource()) {
            System.out.println("Before closing");
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println("After closing");
    }
}

执行结果:

Before closing
SubResource closed
After closing