添加缓存:
//添加商户缓存
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {
@Resource
private StringRedisTemplate stringRedisTemplate;
@Override
public Result queryById(Long id) {
//1.从redis中查询缓存
String shopJson = stringRedisTemplate.opsForValue().get("cache:shop:" + id);
//2.判断是否存在
// isNotBlank不为空,包括""和null
if (StrUtil.isNotBlank(shopJson)) {
//3.存在则直接返回信息
Shop shop = JSONUtil.toBean(shopJson, Shop.class);
return Result.ok(shop);
}
//防止缓存穿透
if ("".equals(shopJson)) {
return Result.fail("店铺不存在");
}
//4.不存在,查询数据库
Shop shop = getById(id);
//5.数据库中数据不存在,返回错误信息
if (shop == null) {
//在redis中设置空值,防止缓存穿透
stringRedisTemplate.opsForValue().set("cache:shop:" +
id,"",2,TimeUnit.MINUTES);
return Result.fail("数据不存在");
}
//6.存在写入redis,返回信息
stringRedisTemplate.opsForValue().set("cache:shop:"+id,JSONUtil.toJsonStr(shop),30L,TimeUnit.MINUTES);
return Result.ok(shop);
}
}
更新缓存 :
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {
@Resource
private StringRedisTemplate stringRedisTemplate;
@Override
@Transactional
public Result update(Shop shop) {
Long id = shop.getId();
if (id == null) {
return Result.fail("店铺id不能为空");
}
//1.更新数据库
updateById(shop);
//2.删除缓存
stringRedisTemplate.delete("cache:shop:"+id);
return Result.ok();
}
}
缓存雪崩:
缓存击穿:
互斥锁解决缓存击穿
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {
@Resource
private StringRedisTemplate stringRedisTemplate;
@Override
public Result queryById(Long id) {
Shop shop = queryWithMutex(id);
if (shop == null) {
return Result.fail("店铺不存在");
}
return Result.ok(shop);
}
//尝试获取锁的方法
private Boolean tryLock(String lockKey) {
//一般比正常业务时间长一点
Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(lockKey, "1", 10, TimeUnit.SECONDS);
//不能直接返回flag,会做拆箱的,可能会出现空指针
return BooleanUtil.isTrue(flag);
}
//释放锁方法
private void unLock(String lockKey) {
stringRedisTemplate.delete(lockKey);
}
//防止缓存击穿
public Shop queryWithMutex(Long id) {
//1.从redis中查询缓存
String shopJson = stringRedisTemplate.opsForValue().get("cache:shop:" + id);
//2.判断是否存在
// isNotBlank不为空,包括""和null
if (StrUtil.isNotBlank(shopJson)) {
//3.存在则直接返回信息
return JSONUtil.toBean(shopJson, Shop.class);
}
//防止缓存穿透
if ("".equals(shopJson)) {
return null;
}
//4.实现缓存重建
//4.1获取互斥锁
String lockKey = "lock:shop:" + id;
Shop shop = null;
try {
Boolean lock = tryLock(lockKey);
//4.2判断获取锁是否成功
if (!lock) {
//4.3不成功,休眠并重试
Thread.sleep(50);
queryWithMutex(id);
}
//5.查询数据库
shop = getById(id);
//6.数据库中数据不存在,返回错误信息
if (shop == null) {
//在redis中设置空值,防止缓存穿透
stringRedisTemplate.opsForValue().set("cache:shop:" + id, "", 2, TimeUnit.MINUTES);
return null;
}
//7.存在写入redis,返回信息
stringRedisTemplate.opsForValue().set("cache:shop:" + id, JSONUtil.toJsonStr(shop), 30L, TimeUnit.MINUTES);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}finally {
//8.释放互斥锁
unLock(lockKey);
}
//9.返回
return shop;
}
}
逻辑过期解决缓存击穿
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {
@Resource
private StringRedisTemplate stringRedisTemplate;
//缓存池
private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);
@Override
public Result queryById(Long id) {
//1.从redis查询商铺缓存
String shopJson = stringRedisTemplate.opsForValue().get("cache:shop:" + id);
//2.判断是否存在
if (StrUtil.isBlank(shopJson)) {
//3.存在,直接返回null
return null;
}
//4.命中,把json反序列化为对象
RedisData redisData = JSONUtil.toBean(shopJson, RedisData.class);
JSONObject data = (JSONObject) redisData.getData();
Shop shop = JSONUtil.toBean(data, Shop.class);
//5.判断是否过期
LocalDateTime expireTime = redisData.getExpireTime();
//过期时间是否在当前时间之后,如果在,就未过期;反正,过期
if (expireTime.isAfter(LocalDateTime.now())) {
//5.1.未过期,返回店铺信息
return Result.ok(shop);
}
//5.2.已过期,需要缓存重建
//6.缓存重建
//6.1.获取互斥锁
String lockKey = "lock:shop:" + id;
//6.2.判断获取锁是否成功
if (tryLock(lockKey)) {
//6.3.成功,开启独立线程,实现缓存重建(线程池做)
CACHE_REBUILD_EXECUTOR.submit(() -> {
try {
//重建缓存
this.saveShopToRedis(id,1800L);
} catch (Exception e) {
throw new RuntimeException(e);
}finally {
//释放锁
unLock(lockKey);
}
});
}
//6.4.返回过期的商铺信息
return Result.ok(shop);
}
//尝试获取锁的方法
private Boolean tryLock(String lockKey) {
//一般比正常业务时间长一点
Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(lockKey, "1", 10, TimeUnit.SECONDS);
//不能直接返回flag,会做拆箱的,可能会出现空指针
return BooleanUtil.isTrue(flag);
}
//释放锁方法
private void unLock(String lockKey) {
stringRedisTemplate.delete(lockKey);
}
public void saveShopToRedis(Long id,Long expireSeconds){
//1.查询店铺数据
Shop shop = getById(id);
//2.封装逻辑过期时间
RedisData redisData = new RedisData();
redisData.setData(shop);
redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));
//3.写入redis
stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id,JSONUtil.toJsonStr(redisData));
}
}