(71条消息) redis缓存_bubbleJessica的博客-CSDN博客
请注意方法中使用了stringRedisTemplate,它是通过IOC注入进来的,IOC是通过new的方式创建bean,new出来的对象是在堆里面的,static修饰的东西是优先于对象存在的,这就是工具类方法不使用static的原因
package com.hmdp.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 javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import static com.hmdp.utils.RedisConstants.*;
//spring去维护就行 记录工具类相关日志操作
@Component
@Slf4j
public class CacheClient {
@Resource
private StringRedisTemplate stringRedisTemplate;
// 带上过期时间 模仿spring玩法基本与springAPI一致
public void set(String key, Object value, Long time, TimeUnit unit){
stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value),time,unit);
}
// 带上过期时间 模仿spring玩法基本与springAPI一致
public void setWithLogicalExpire(String key, Object value, Long time, TimeUnit unit){
// 设置逻辑过期
RedisData redisData = new RedisData();
redisData.setData(value);
redisData.setExpireTime(LocalDateTime.now().plusSeconds(unit.toSeconds(time)));
// 写入redis
stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value));
}
// 缓存穿透
public <R,ID> R queryWithPassThrough(String keyPrefix, ID id, Class<R> type, Function<ID,R> doFallback,Long time, TimeUnit unit){
// 1.从redis中查询商铺缓存
String key=keyPrefix+id;
String json = stringRedisTemplate.opsForValue().get(key);
// 2.1 判断是否存在(数据真实存在)
if (StrUtil.isNotBlank(json)) {
// 3.1 存在直接返回
return JSONUtil.toBean(json,type);
}
// 3.2 存在(数据为空字符串),返回错误信息
// 等价于"".equals(shopJson)
if (json!=null){
return null;
}
// 4.不存在,则去数据库查询
R r =doFallback.apply(id);
// 5.如果找不到,则返回错误信息
if (r==null){
// 将空值写入redis
stringRedisTemplate.opsForValue().set(key,"",CACHE_NULL_TTL,TimeUnit.MINUTES);
// 返回错误信息
return null;
}
// 6.如果找到,存放到redis当中
this.set(key,r,time,unit);
// 7.返回
return r;
}
// 线程池
private static final ExecutorService CACHE_REBUILD_EXECUTOR= Executors.newFixedThreadPool(10);
// 缓存击穿2
public <R,ID> R queryWithLogicalExpire(String keyPrefix,ID id,Class<R> type,Function<ID,R> dbFallback, Long time, TimeUnit unit){
// 1.从redis中查询商铺缓存
String key=keyPrefix+id;
String json = stringRedisTemplate.opsForValue().get(key);
// 2.1 判断是否存在(数据真实存在)
if (StrUtil.isBlank(json)) {
// 3.1 存在,直接返回null
return null;
}
// 4.命中,需要先把json反序列化为对象
RedisData redisData = JSONUtil.toBean(json, RedisData.class);
// Object data = redisData.getData();
// 返回的是Object类型但我们需要强转 以便转换成需要Shop类型
JSONObject data = (JSONObject) redisData.getData();
R r = JSONUtil.toBean(data, type);
LocalDateTime expireTime = redisData.getExpireTime();
// 5.判断是否过期
if (expireTime.isAfter(LocalDateTime.now())){
// 5.1 未过期,直接返回店铺信息(旧的)
return r;
}
// 5.2 已过期,需要缓存重建
// 6.缓存重建
// 6.1 获取互斥锁
String lockKey= LOCK_SHOP_KEY+id;
// 6.2 判断是否获取锁成功
boolean isLock = tryLock(lockKey);
if (isLock){
// 这里需要再次检查redis缓存是否过期(获取到的锁刚好是上一个线程缓存重建释放的)
if (expireTime.isAfter(LocalDateTime.now())){
// 5.1 未过期,直接返回店铺信息(旧的)
return r;
}
// 6.3 成功,开启独立线程,实现缓存重建
CACHE_REBUILD_EXECUTOR.submit(()-> {
try {
// 重建缓存
// 查询数据库
R r1 = dbFallback.apply(id);
// 写入redis
this.setWithLogicalExpire(key,r1,time,unit);
}catch (Exception e){
throw new RuntimeException(e);
}finally {
// 释放锁
unlock(lockKey);
}
});
}
// 6.4 返回过期的商铺信息
return r;
}
// 尝试获取锁
private boolean tryLock(String key){
Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
return BooleanUtil.isTrue(flag);
}
// 释放锁
private void unlock(String key){
stringRedisTemplate.delete(key);
}
}
参数函数式编程<参数类型,返回值类型>
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {
@Resource
private StringRedisTemplate stringRedisTemplate;
@Resource
private CacheClient cacheClient;
@Override
public Result queryById(Long id) {
// 缓存穿透
// Shop shop = cacheClient.queryWithPassThrough(CACHE_SHOP_KEY,id,Shop.class,id2->getById(id2),CACHE_SHOP_TTL,TimeUnit.MINUTES);
// Shop shop = cacheClient.queryWithPassThrough(CACHE_SHOP_KEY,id,Shop.class,this::getById,CACHE_SHOP_TTL,TimeUnit.MINUTES);
// 缓存击穿
// Shop shop = queryWithMutex(id);
// 缓存击穿2
//Shop shop = queryWithLogicalExpire(id);
Shop shop = cacheClient.queryWithLogicalExpire(CACHE_SHOP_KEY, id, Shop.class, this::getById, CACHE_SHOP_TTL, TimeUnit.MINUTES);
if (shop==null){
Result.fail("店铺不存在!");
}
return Result.ok(shop);
}
}
注意在检测缓存击穿功能时需要先测试类实现一下
package com.hmdp;
import com.hmdp.entity.Shop;
import com.hmdp.service.impl.ShopServiceImpl;
import com.hmdp.utils.CacheClient;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;
import static com.hmdp.utils.RedisConstants.CACHE_SHOP_KEY;
@SpringBootTest
class HmDianPingApplicationTests {
@Resource
private CacheClient cacheClient;
@Resource
private ShopServiceImpl shopService;
@Test
void testSaveShop() throws InterruptedException {
//shopService.saveShop2Redis(1L,10L);
Shop shop = shopService.getById(1L);
cacheClient.setWithLogicalExpire(CACHE_SHOP_KEY+1L,shop,10L, TimeUnit.SECONDS);
}
}