之前你可能是这样使用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
网友评论