From 1302ec09b5b2def90b3f22496d4b55c3b3f9ab81 Mon Sep 17 00:00:00 2001 From: wanghu Date: Wed, 19 Aug 2026 20:22:40 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E5=A4=8Dredis=20=E6=97=B6=E9=97=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controller/api/CacheController.java | 41 +++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/src/main/java/com/yunhai/bschclassmanage/controller/api/CacheController.java b/src/main/java/com/yunhai/bschclassmanage/controller/api/CacheController.java index 26775e7..46c4916 100644 --- a/src/main/java/com/yunhai/bschclassmanage/controller/api/CacheController.java +++ b/src/main/java/com/yunhai/bschclassmanage/controller/api/CacheController.java @@ -10,6 +10,7 @@ import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.data.redis.serializer.RedisSerializer; import org.springframework.web.bind.annotation.*; import java.util.Arrays; @@ -96,9 +97,49 @@ public class CacheController extends BaseController { break; } result.put("value", value); + + // 缓存值大小(字节):用 ValueSerializer 重新序列化得到实际存储体积 + long size = 0; + try { + @SuppressWarnings("unchecked") + RedisSerializer valueSerializer = (RedisSerializer) redisTemplate.getValueSerializer(); + if (valueSerializer != null && value != null) { + byte[] raw = valueSerializer.serialize(value); + size = (raw != null) ? raw.length : 0; + } + } catch (Exception ignore) { + size = 0; + } + result.put("size", size); + + // 可读过期时间(expire 仍为原始秒:-1 永不过期,-2 不存在) + long ttl = redisTemplate.getExpire(key, TimeUnit.SECONDS); + result.put("expireText", formatTtl(ttl)); return result; } + /** + * 将剩余秒数格式化为可读文本 + */ + private String formatTtl(long ttl) { + if (ttl == -1) { + return "永不过期"; + } + if (ttl == -2) { + return "已过期/不存在"; + } + if (ttl < 60) { + return ttl + " 秒"; + } + if (ttl < 3600) { + return (ttl / 60) + " 分 " + (ttl % 60) + " 秒"; + } + if (ttl < 86400) { + return (ttl / 3600) + " 小时 " + ((ttl % 3600) / 60) + " 分"; + } + return (ttl / 86400) + " 天 " + ((ttl % 86400) / 3600) + " 小时"; + } + /** * 根据模式匹配查询 key 列表(如 school_class_*),方便先找到 key 再查看内容 *