From 0f202cb07643f1a9504a25d6d8014a522373016c Mon Sep 17 00:00:00 2001 From: LamGC Date: Fri, 24 Apr 2020 00:42:41 +0800 Subject: [PATCH] =?UTF-8?q?[Update]=20RedisPoolCacheStore=20=E4=BC=98?= =?UTF-8?q?=E5=8C=96=E4=BB=A3=E7=A0=81;?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../cgj/bot/cache/RedisPoolCacheStore.java | 43 +++++++++++-------- 1 file changed, 24 insertions(+), 19 deletions(-) diff --git a/src/main/java/net/lamgc/cgj/bot/cache/RedisPoolCacheStore.java b/src/main/java/net/lamgc/cgj/bot/cache/RedisPoolCacheStore.java index 7c2eb3e..8aef9a6 100644 --- a/src/main/java/net/lamgc/cgj/bot/cache/RedisPoolCacheStore.java +++ b/src/main/java/net/lamgc/cgj/bot/cache/RedisPoolCacheStore.java @@ -9,6 +9,7 @@ import redis.clients.jedis.*; import java.net.URI; import java.util.Date; import java.util.Objects; +import java.util.Set; import java.util.function.Consumer; import java.util.function.Function; @@ -50,29 +51,27 @@ public abstract class RedisPoolCacheStore implements CacheStore { @Override public void update(String key, T value, Date expire) { - Jedis jedis = jedisPool.getResource(); - jedis.set(keyPrefix + key, parse(value)); - if(expire != null) { - jedis.pexpireAt(keyPrefix + key, expire.getTime()); - log.debug("已设置Key {} 的过期时间(Expire: {})", key, expire.getTime()); + try (Jedis jedis = jedisPool.getResource()) { + jedis.set(keyPrefix + key, parse(value)); + if(expire != null) { + jedis.pexpireAt(keyPrefix + key, expire.getTime()); + log.debug("已设置Key {} 的过期时间(Expire: {})", key, expire.getTime()); + } } - jedis.close(); } @Override public T getCache(String key) { - Jedis jedis = jedisPool.getResource(); - T result = analysis(jedis.get(keyPrefix + key)); - jedis.close(); - return result; + try (Jedis jedis = jedisPool.getResource()) { + return analysis(jedis.get(keyPrefix + key)); + } } @Override public boolean exists(String key) { - Jedis jedis = jedisPool.getResource(); - boolean result = jedis.exists(keyPrefix + key); - jedis.close(); - return result; + try (Jedis jedis = jedisPool.getResource()) { + return jedis.exists(keyPrefix + key); + } } @Override @@ -82,11 +81,17 @@ public abstract class RedisPoolCacheStore implements CacheStore { @Override public boolean clear() { - Jedis jedis = jedisPool.getResource(); - String result = jedis.flushDB(); - jedis.close(); - log.info("flushDB返回结果: {}", result); - return true; + try (Jedis jedis = jedisPool.getResource()) { + String result = jedis.flushDB(); + log.info("flushDB返回结果: {}", result); + return true; + } + } + + public Set keys() { + try (Jedis jedis = jedisPool.getResource()) { + return jedis.keys(keyPrefix + "*"); + } } /**