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公衆號

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章