key = getKeyPrefix() + key
+ * @param cacheKey CacheKey 对象.
+ * @return 返回 Key 前缀.
+ */
+ protected String getKeyString(CacheKey cacheKey) {
+ return getKeyPrefix() + cacheKey.join(RedisUtils.KEY_SEPARATOR);
+ }
+
+ /**
+ * 获取 Key 的完整前缀.
+ * @return 返回完整前缀.
+ */
+ protected abstract String getKeyPrefix();
+
+ @Override
+ public boolean setTimeToLive(CacheKey key, long ttl) {
+ String keyString = getKeyString(key);
+ return RedisConnectionPool.executeRedis(jedis -> {
+ Long result;
+ if (ttl >= 0) {
+ result = jedis.pexpire(keyString, ttl);
+ } else {
+ result = jedis.persist(keyString);
+ }
+ return result == RedisUtils.RETURN_CODE_OK;
+ });
+ }
+
+ @Override
+ public long getTimeToLive(CacheKey key) {
+ return RedisConnectionPool.executeRedis(jedis -> {
+ Long ttl = jedis.pttl(getKeyString(key));
+ return ttl < 0 ? -1 : ttl;
+ });
+ }
+
+ @Override
+ public long size() {
+ return RedisConnectionPool.executeRedis(Jedis::dbSize);
+ }
+
+ @Override
+ public boolean clear() {
+ return RedisConnectionPool.executeRedis(jedis -> RedisUtils.isOk(jedis.flushDB()));
+ }
+
+ @Override
+ public boolean exists(CacheKey key) {
+ return RedisConnectionPool.executeRedis(jedis -> jedis.exists(getKeyString(key)));
+ }
+
+ @Override
+ public boolean remove(CacheKey key) {
+ return RedisConnectionPool.executeRedis(jedis -> jedis.del(getKeyString(key)) == RedisUtils.RETURN_CODE_OK);
+ }
+
+ @Override
+ public Set 注意, 需回收 Jedis 对象, 否则可能会耗尽连接池导致后续操作受到影响.
+ * @return 返回可用的 Jedis 连接.
+ */
+ public static Jedis getConnection() {
+ JedisPool pool = POOL.get();
+ if (pool == null || pool.isClosed()) {
+ reconnectRedis();
+ pool = POOL.get();
+ if (pool == null) {
+ throw new IllegalStateException("Redis connection lost");
+ }
+ }
+ return pool.getResource();
+ }
+
+ /**
+ * 执行 Redis 操作并返回相关值.
+ * 本方法会自动回收 Jedis.
+ * @param function 待运行的操作.
+ * @param