2026-06-26 04:51:07 +08:00
|
|
|
package com.njcn.middle.cache.template;
|
|
|
|
|
|
2026-06-26 04:55:42 +08:00
|
|
|
import cn.hutool.core.util.IdUtil;
|
2026-06-26 04:51:07 +08:00
|
|
|
import com.alibaba.fastjson.TypeReference;
|
|
|
|
|
import com.njcn.middle.cache.autoconfig.RedisCacheProperties;
|
2026-06-26 04:55:42 +08:00
|
|
|
import com.njcn.middle.cache.constant.CacheConstant;
|
2026-06-26 04:51:07 +08:00
|
|
|
import com.njcn.middle.cache.support.CacheKeyBuilder;
|
|
|
|
|
import com.njcn.middle.cache.support.CacheValueCodec;
|
|
|
|
|
import lombok.extern.slf4j.Slf4j;
|
|
|
|
|
import org.springframework.data.redis.core.StringRedisTemplate;
|
2026-06-26 04:55:42 +08:00
|
|
|
import org.springframework.data.redis.core.script.DefaultRedisScript;
|
2026-06-26 04:51:07 +08:00
|
|
|
|
2026-06-26 04:55:42 +08:00
|
|
|
import java.time.Duration;
|
|
|
|
|
import java.util.Collections;
|
2026-06-26 04:51:07 +08:00
|
|
|
import java.util.concurrent.ThreadLocalRandom;
|
|
|
|
|
import java.util.concurrent.TimeUnit;
|
|
|
|
|
import java.util.function.Function;
|
2026-06-26 04:55:42 +08:00
|
|
|
import java.util.function.Supplier;
|
2026-06-26 04:51:07 +08:00
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Redis 缓存增强模板。
|
|
|
|
|
*
|
|
|
|
|
* <p>底层 {@link StringRedisTemplate} 存字符串,fastjson 序列化。本类(Task 4)实现读写基础;
|
|
|
|
|
* {@code getOrLoad} 三防(穿透/雪崩/击穿)由 Task 5 追加。
|
|
|
|
|
*/
|
|
|
|
|
@Slf4j
|
|
|
|
|
public class RedisCacheEnhanceTemplate {
|
|
|
|
|
|
2026-06-26 04:55:42 +08:00
|
|
|
/** 释放锁 Lua:token 匹配才删,防误删他人锁。 */
|
|
|
|
|
private static final DefaultRedisScript<Long> UNLOCK_SCRIPT = new DefaultRedisScript<>(
|
|
|
|
|
"if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end",
|
|
|
|
|
Long.class);
|
|
|
|
|
|
2026-06-26 04:51:07 +08:00
|
|
|
private final StringRedisTemplate redis;
|
|
|
|
|
private final CacheKeyBuilder keyBuilder;
|
|
|
|
|
private final CacheValueCodec codec;
|
|
|
|
|
private final RedisCacheProperties props;
|
|
|
|
|
|
|
|
|
|
public RedisCacheEnhanceTemplate(StringRedisTemplate redis, CacheKeyBuilder keyBuilder,
|
|
|
|
|
CacheValueCodec codec, RedisCacheProperties props) {
|
|
|
|
|
this.redis = redis;
|
|
|
|
|
this.keyBuilder = keyBuilder;
|
|
|
|
|
this.codec = codec;
|
|
|
|
|
this.props = props;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// ---- 写 ----
|
|
|
|
|
|
|
|
|
|
public void set(String key, Object value) {
|
|
|
|
|
set(key, value, props.getDefaultTtlSeconds());
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public void set(String key, Object value, long ttlSeconds) {
|
|
|
|
|
redis.opsForValue().set(keyBuilder.build(key), codec.encode(value),
|
|
|
|
|
applyJitter(ttlSeconds), TimeUnit.SECONDS);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// ---- 读 ----
|
|
|
|
|
|
|
|
|
|
public <T> T get(String key, Class<T> type) {
|
|
|
|
|
return doGet(key, raw -> codec.decode(raw, type));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public <T> T get(String key, TypeReference<T> type) {
|
|
|
|
|
return doGet(key, raw -> codec.decode(raw, type));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private <T> T doGet(String key, Function<String, T> decoder) {
|
|
|
|
|
String dataKey = keyBuilder.build(key);
|
|
|
|
|
String raw = redis.opsForValue().get(dataKey);
|
|
|
|
|
if (raw == null || codec.isNullSentinel(raw)) {
|
|
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
T value;
|
|
|
|
|
try {
|
|
|
|
|
value = decoder.apply(raw);
|
|
|
|
|
} catch (RuntimeException e) {
|
|
|
|
|
throw new IllegalStateException("cache decode failed, key=" + dataKey, e);
|
|
|
|
|
}
|
|
|
|
|
slidingTouch(dataKey);
|
|
|
|
|
return value;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// ---- 删 / 判存 ----
|
|
|
|
|
|
|
|
|
|
public boolean delete(String key) {
|
|
|
|
|
return Boolean.TRUE.equals(redis.delete(keyBuilder.build(key)));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public boolean exists(String key) {
|
|
|
|
|
return Boolean.TRUE.equals(redis.hasKey(keyBuilder.build(key)));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// ---- 续期 ----
|
|
|
|
|
|
|
|
|
|
public boolean expire(String key, long ttlSeconds) {
|
|
|
|
|
return Boolean.TRUE.equals(
|
|
|
|
|
redis.expire(keyBuilder.build(key), applyJitter(ttlSeconds), TimeUnit.SECONDS));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// ---- 内部 ----
|
|
|
|
|
|
|
|
|
|
/** 滑动过期:开启时对已存在的真实值 key 续期(直接对 dataKey 操作,失败忽略)。 */
|
|
|
|
|
private void slidingTouch(String dataKey) {
|
|
|
|
|
if (!props.isSlidingExpireEnabled()) {
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
try {
|
|
|
|
|
redis.expire(dataKey, applyJitter(props.getDefaultTtlSeconds()), TimeUnit.SECONDS);
|
|
|
|
|
} catch (RuntimeException e) {
|
|
|
|
|
log.warn("[redis-cache] sliding expire failed key={}", dataKey, e);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/** 在原 TTL 上叠加 [0, ttl*ratio] 的随机抖动(只增不减);ratio<=0 或 ttl<=0 时原样返回。 */
|
|
|
|
|
long applyJitter(long ttlSeconds) {
|
|
|
|
|
double ratio = props.getJitterRatio();
|
|
|
|
|
if (ratio <= 0 || ttlSeconds <= 0) {
|
|
|
|
|
return ttlSeconds;
|
|
|
|
|
}
|
|
|
|
|
long bound = (long) (ttlSeconds * ratio);
|
|
|
|
|
if (bound <= 0) {
|
|
|
|
|
return ttlSeconds;
|
|
|
|
|
}
|
|
|
|
|
return ttlSeconds + ThreadLocalRandom.current().nextLong(bound + 1);
|
|
|
|
|
}
|
2026-06-26 04:55:42 +08:00
|
|
|
|
|
|
|
|
// ---- 读取或回源(三防核心)----
|
|
|
|
|
|
|
|
|
|
public <T> T getOrLoad(String key, Class<T> type, Supplier<T> loader) {
|
|
|
|
|
return getOrLoad(key, type, props.getDefaultTtlSeconds(), loader);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public <T> T getOrLoad(String key, Class<T> type, long ttlSeconds, Supplier<T> loader) {
|
|
|
|
|
return doGetOrLoad(key, raw -> codec.decode(raw, type), ttlSeconds, loader);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public <T> T getOrLoad(String key, TypeReference<T> type, long ttlSeconds, Supplier<T> loader) {
|
|
|
|
|
return doGetOrLoad(key, raw -> codec.decode(raw, type), ttlSeconds, loader);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private <T> T doGetOrLoad(String key, Function<String, T> decoder, long ttlSeconds, Supplier<T> loader) {
|
|
|
|
|
String dataKey = keyBuilder.build(key);
|
|
|
|
|
|
|
|
|
|
Lookup<T> r = tryGet(dataKey, decoder);
|
|
|
|
|
if (r.hit) {
|
|
|
|
|
if (r.realValue) {
|
|
|
|
|
slidingTouch(dataKey);
|
|
|
|
|
}
|
|
|
|
|
return r.value;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
RedisCacheProperties.Breakdown bd = props.getBreakdown();
|
|
|
|
|
if (!bd.isEnabled()) {
|
|
|
|
|
return loadAndCache(dataKey, ttlSeconds, loader);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
String lockKey = dataKey + CacheConstant.LOCK_SUFFIX;
|
|
|
|
|
String token = IdUtil.fastSimpleUUID();
|
|
|
|
|
boolean locked = Boolean.TRUE.equals(redis.opsForValue()
|
|
|
|
|
.setIfAbsent(lockKey, token, Duration.ofMillis(bd.getLockTtlMs())));
|
|
|
|
|
|
|
|
|
|
if (locked) {
|
|
|
|
|
try {
|
|
|
|
|
Lookup<T> r2 = tryGet(dataKey, decoder); // double-check
|
|
|
|
|
if (r2.hit) {
|
|
|
|
|
if (r2.realValue) {
|
|
|
|
|
slidingTouch(dataKey);
|
|
|
|
|
}
|
|
|
|
|
return r2.value;
|
|
|
|
|
}
|
|
|
|
|
return loadAndCache(dataKey, ttlSeconds, loader);
|
|
|
|
|
} finally {
|
|
|
|
|
releaseLock(lockKey, token);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 未抢到锁:自旋等待重读,超时降级直接回源
|
|
|
|
|
long waited = 0;
|
|
|
|
|
while (waited < bd.getWaitTimeoutMs()) {
|
|
|
|
|
sleep(bd.getWaitIntervalMs());
|
|
|
|
|
waited += bd.getWaitIntervalMs();
|
|
|
|
|
Lookup<T> r3 = tryGet(dataKey, decoder);
|
|
|
|
|
if (r3.hit) {
|
|
|
|
|
if (r3.realValue) {
|
|
|
|
|
slidingTouch(dataKey);
|
|
|
|
|
}
|
|
|
|
|
return r3.value;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
log.warn("[redis-cache] breakdown wait timeout, fallback to loader, key={}", key);
|
|
|
|
|
return loader.get();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/** 读取三态:未命中 / 命中空值标记 / 命中真实值;反序列化失败当未命中降级。 */
|
|
|
|
|
private <T> Lookup<T> tryGet(String dataKey, Function<String, T> decoder) {
|
|
|
|
|
String raw = redis.opsForValue().get(dataKey);
|
|
|
|
|
if (raw == null) {
|
|
|
|
|
return Lookup.miss();
|
|
|
|
|
}
|
|
|
|
|
if (codec.isNullSentinel(raw)) {
|
|
|
|
|
return Lookup.nullHit();
|
|
|
|
|
}
|
|
|
|
|
try {
|
|
|
|
|
return Lookup.hit(decoder.apply(raw));
|
|
|
|
|
} catch (RuntimeException e) {
|
|
|
|
|
log.warn("[redis-cache] decode failed, treat as miss key={}", dataKey, e);
|
|
|
|
|
return Lookup.miss();
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/** 回源并写缓存:null → 空值标记(穿透);非 null → 抖动 TTL(雪崩)。 */
|
|
|
|
|
private <T> T loadAndCache(String dataKey, long ttlSeconds, Supplier<T> loader) {
|
|
|
|
|
T value = loader.get();
|
|
|
|
|
if (value == null) {
|
|
|
|
|
redis.opsForValue().set(dataKey, CacheConstant.NULL_SENTINEL,
|
|
|
|
|
props.getNullTtlSeconds(), TimeUnit.SECONDS);
|
|
|
|
|
} else {
|
|
|
|
|
redis.opsForValue().set(dataKey, codec.encode(value),
|
|
|
|
|
applyJitter(ttlSeconds), TimeUnit.SECONDS);
|
|
|
|
|
}
|
|
|
|
|
return value;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private void releaseLock(String lockKey, String token) {
|
|
|
|
|
try {
|
|
|
|
|
redis.execute(UNLOCK_SCRIPT, Collections.singletonList(lockKey), token);
|
|
|
|
|
} catch (RuntimeException e) {
|
|
|
|
|
log.warn("[redis-cache] release lock failed lockKey={}", lockKey, e);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private static void sleep(long ms) {
|
|
|
|
|
try {
|
|
|
|
|
Thread.sleep(ms);
|
|
|
|
|
} catch (InterruptedException e) {
|
|
|
|
|
Thread.currentThread().interrupt();
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/** 读取三态载体(对外不暴露)。 */
|
|
|
|
|
private static final class Lookup<T> {
|
|
|
|
|
final boolean hit; // 命中(真实值或空值标记)
|
|
|
|
|
final boolean realValue; // 命中且为真实值
|
|
|
|
|
final T value;
|
|
|
|
|
|
|
|
|
|
private Lookup(boolean hit, boolean realValue, T value) {
|
|
|
|
|
this.hit = hit;
|
|
|
|
|
this.realValue = realValue;
|
|
|
|
|
this.value = value;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
static <T> Lookup<T> miss() {
|
|
|
|
|
return new Lookup<>(false, false, null);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
static <T> Lookup<T> nullHit() {
|
|
|
|
|
return new Lookup<>(true, false, null);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
static <T> Lookup<T> hit(T v) {
|
|
|
|
|
return new Lookup<>(true, true, v);
|
|
|
|
|
}
|
|
|
|
|
}
|
2026-06-26 04:51:07 +08:00
|
|
|
}
|