美文网首页
如何更加优雅的使用Jedis

如何更加优雅的使用Jedis

作者: 出水肥龙 | 来源:发表于2020-01-19 15:17 被阅读0次

之前你可能是这样使用redis

 public Long hset(String key, String field, String value) {
        Jedis jedis = null;
        try {
            jedis = pool.getResource();
            return jedis.hset(key, field, value);
        } catch (Exception e) {
            logger.error("Jedis exp", e);
            throw e;
        } finally {
            returnResource(jedis);
        }
    }

    /**
     * 返还到连接池
     *
     * @param jedis
     */
    public static void returnResource(Jedis jedis) {
        if (jedis != null) {
            try {
                jedis.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            jedis = null;
        }
    }

但是java7引入了新特性
try(){ }

就可以用下面的代码来替代了

public Long hset(final String key, final String field, final String value) {
        try (Jedis jedis = jedisPool.getResource()) {
            return jedis.hset(key, field, value);
        }
    }

其实不仅仅是redis,类似FileInputStream之类的都可以这样用。try括号内的资源会在try语句结束后自动释放,前提是这些可关闭的资源必须实现 java.lang.AutoCloseable 接口。
当然jedis自己已经实现了

public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommands,
    AdvancedJedisCommands, ScriptingCommands, BasicCommands, ClusterCommands, SentinelCommands
public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKeyBinaryCommands,
    AdvancedBinaryJedisCommands, BinaryScriptingCommands, Closeable 
public interface Closeable extends AutoCloseable

相关文章

网友评论

      本文标题:如何更加优雅的使用Jedis

      本文链接:https://www.haomeiwen.com/subject/drmrzctx.html