Jedis 在 Java7 之后无需手动调用 close 释放连接 try-with-resources 内幕

微信公众号:molashaonian

Jedis 用完是否需要手动 close?

  • 一般情况下,我们在使用完连接资源后都要 close 关闭连接,释放资源。这么常用的方法,基于习惯,Java 在 jdk1.7 之后为我们提供了一个很好的方法
    try-with-resources Statement ,我们不再需要手动调用 close 方法,也可以释放连接。
  • 此处以 Jedis 为例子,说下该方法的使用,如果我们的 Jedis 是通过 jedisPool.getResource() 从连接池获取的话,调用 close 方法将会把连接归还到连接池。否则,断开与 Redis 的连接。

try-with-resources Statement

  • 使用 try-with-resources Statement " try(resource) ",它会自动关闭括号内的资源(resources),不用手动添加代码 xx.close();
  • 实际上是有一个隐式 finally 中调用了 resource.close();关闭了资源。后面贴出编译后的代码可见。
  • 使用这个方法前提是,resource 必须继承自 java.lang.AutoCloseable
  • 不单 Jedis 可用,InputStream,OutputStream 等也可用,只要继承了 AutoCloseable
Java 代码:
/**
 * Sets nx.
 *
 * @param key                the key
 * @param val                the val
 * @param expireMilliseconds the expire milliseconds
 * @return the nx
 */
public static boolean setNx(String key, Object val, Long expireMilliseconds) {
    try (Jedis jedis = getJedis()) {
        String result = jedis.set(key(key), jsonTools.toJson(val), "NX", "PX", expireMilliseconds);
        return ok(result);
    } catch (Exception e) {
        log.error("Redis error:{}", ExceptionTools.getExceptionStackTrace(e));
        return false;
    }

}

在 try() 括号里面获取 jedis 连接即可

编译后的 class 代码:

public static boolean setNx(String key, Object val, Long expireMilliseconds) {
    try {
        Jedis jedis = getJedis();
        Throwable var4 = null;

        boolean var6;
        try {
            String result = jedis.set(key(key), jsonTools.toJson(val), "NX", "PX", expireMilliseconds);
            var6 = ok(result);
        } catch (Throwable var16) {
            var4 = var16;
            throw var16;
        } finally {
            if (jedis != null) {
                if (var4 != null) {
                    try {
                        jedis.close();
                    } catch (Throwable var15) {
                        var4.addSuppressed(var15);
                    }
                } else {
                    jedis.close();
                }
            }

        }

        return var6;
    } catch (Exception var18) {
        log.error("Redis error:{}", ExceptionTools.getExceptionStackTrace(var18));
        return false;
    }
}

编译之后,自动加上了 finally 方法,并且执行 jedis.close() 方法

Reference

The try-with-resources Statement
Java | 原来 try 还可以这样用啊?!

下面的是我的公众号二维码图片,欢迎关注。

图注:molashaonian公众号

posted on   EvanLong  阅读(1170)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
历史上的今天:
2018-05-06 绝对完全跨域统一单点登录登出

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示