package com.xkj.org.utils;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
@Slf4j
@Component
public class CacheClient {
private StringRedisTemplate stringRedisTemplate;
public CacheClient(StringRedisTemplate stringRedisTemplate) {
this.stringRedisTemplate = stringRedisTemplate;
}
/**
* 向redis中添加数据,设置有效期
* @param key 键
* @param value 缓存数据
* @param time 失效时间
* @param timeUnit 时间单位
*/
public void set(String key, Object value, Long time, TimeUnit timeUnit) {
stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value), time, timeUnit);
}
/**
* 向redis中添加数据,设置逻辑过期时间
* @param key 键
* @param value 缓存数据
* @param time 逻辑失效时间
* @param timeUnit 时间单位
*/
public void setWithLogicalExpire(String key, Object value, Long time, TimeUnit timeUnit) {
RedisData redisData = new RedisData();
redisData.setData(value);
redisData.setExpireTime(LocalDateTime.now().plusSeconds(timeUnit.toSeconds(time)));
stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData));
}
/**
* 从redis中查询数据,解决缓存穿透
* @param keyPrefix 缓存key的前缀
* @param id 主键标识,用于数据库查询数据
* @param type 数据转成对象的类型
* @param dbFallback 查询数据库的回调函数
* @param time 缓存数据的有效期
* @param timeUnit 缓存数据的时间单位
* @param <R> 数据对象
* @param <ID> 数据对象的唯一标识
* @return
*/
public <R, ID> R queryWithPassThrough(String keyPrefix, ID id, Class<R> type, Function<ID, R> dbFallback
, Long time, TimeUnit timeUnit) {
String key = keyPrefix + id;
String json = stringRedisTemplate.opsForValue().get(key);
if(StrUtil.isNotBlank(json)) {
return JSONUtil.toBean(json, type);
}
if(json != null) {
//缓存了空值,直接返回
return null;
}
//查询数据库,使用函数式接口,function 有参数有返回值
R r = dbFallback.apply(id);
if (r == null) {
//数据库查询不到,则将“”存储到redis中,缓存空值
stringRedisTemplate.opsForValue().set(key, "", RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
return null;
}
//查询到数据,则存入redis
this.set(key, JSONUtil.toJsonStr(r), time, timeUnit);
return r;
}
//创建线程池
private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);
/**
* 解决缓存击穿-逻辑过期
* @param keyPrefix 键的前缀
* @param id 主键id
* @param type 数据转成对象的类型
* @param dbFallback 查询数据库的回调函数
* @param time 缓存数据的有效期
* @param timeUnit 缓存数据的时间单位
* @param <R> 数据对象
* @param <ID> 数据对象的唯一标识
* @return
*/
public <R, ID> R queryWithLogicalExpire(
String keyPrefix, ID id, Class<R> type, Function<ID, R> dbFallback
, Long time, TimeUnit timeUnit) {
String key = keyPrefix + id;
String json = stringRedisTemplate.opsForValue().get(key);
if(StrUtil.isBlank(json)) {
return null;
}
RedisData redisData = JSONUtil.toBean(json, RedisData.class);
R r = JSONUtil.toBean((JSONObject) redisData.getData(), type);
LocalDateTime expireTime = redisData.getExpireTime();
if (expireTime.isAfter(LocalDateTime.now())) {
//逻辑未过期
return r;
}
//逻辑已过期,重建缓存
String lockKey = RedisConstants.LOCK_SHOP_KEY + id;
boolean isLock = tryLock(lockKey);
if(isLock) {
//获取锁成功,在判断一次缓存是否逻辑过期,doubleCheck
json = stringRedisTemplate.opsForValue().get(key);
redisData = JSONUtil.toBean(json, RedisData.class);
r = JSONUtil.toBean((JSONObject) redisData.getData(), type);
expireTime = redisData.getExpireTime();
if (expireTime.isAfter(LocalDateTime.now())) {
//逻辑未过期
return r;
}
//获取锁成功,单独开启一个线程执行缓存重建
CACHE_REBUILD_EXECUTOR.submit(() -> {
try{
R apply = dbFallback.apply(id);
this.setWithLogicalExpire(key, apply, time, timeUnit);
}catch (Exception e) {
e.printStackTrace();
}finally {
unLock(lockKey);
}
});
}
return r;
}
/**
* 尝试加锁
* @return
*/
public boolean tryLock(String key) {
//setnx命令
Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
//这里会自动拆箱,防止flag为null报空指针异常
return BooleanUtil.isTrue(flag);
}
/**
* 释放锁
* @param key
*/
public void unLock(String key) {
stringRedisTemplate.delete(key);
}
}
@SpringBootTest
public class SpringBootDataRedisTest {
@Autowired
private ShopServiceImpl shopService;
@Resource
private CacheClient cacheClient;
@Test
void testSaveShop1() {
Shop shop = shopService.getById(1L);
cacheClient.setWithLogicalExpire(RedisConstants.CACHE_SHOP_KEY + 1, shop, 10L, TimeUnit.SECONDS);
}
}