feat(cache): 值编解码器(fastjson 序列化 + 空值标记)

This commit is contained in:
root
2026-06-26 04:41:02 +08:00
parent ce370afa83
commit ecbdfd8907
2 changed files with 101 additions and 0 deletions

View File

@@ -0,0 +1,37 @@
package com.njcn.middle.cache.support;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.njcn.middle.cache.constant.CacheConstant;
/**
* 缓存值编解码:对象 ↔ 字符串(fastjson),并承载空值标记。
*
* <p>解码失败直接抛 fastjson 异常({@link RuntimeException}),由调用方决定显式暴露(public get)
* 还是当未命中降级(getOrLoad 内部)。
*/
public class CacheValueCodec {
/** 对象 → 字符串:null → 空值标记;否则 fastjson 序列化。 */
public String encode(Object value) {
if (value == null) {
return CacheConstant.NULL_SENTINEL;
}
return JSON.toJSONString(value);
}
/** 是否空值标记。 */
public boolean isNullSentinel(String raw) {
return CacheConstant.NULL_SENTINEL.equals(raw);
}
/** 字符串 → 对象(Class)。 */
public <T> T decode(String raw, Class<T> type) {
return JSON.parseObject(raw, type);
}
/** 字符串 → 对象(TypeReference,支持泛型)。 */
public <T> T decode(String raw, TypeReference<T> type) {
return JSON.parseObject(raw, type);
}
}