public Result queryShopById(Long id) {
String shopKey = CACHE_SHOP_KEY + id;
// 1. 从Redis查询商铺缓存
String cacheShop = stringRedisTemplate.opsForValue().get(shopKey);
// 2. 判断缓存是否命中
if(StringUtils.isNotBlank(cacheShop)){
// 3. 命中, 返回商铺信息
Shop shop = JSON.parseObject(cacheShop, Shop.class);
return Result.ok(shop);
}
// 4. 未命中, 根据id查询数据库
Shop shop = getById(id);
// 5. 判断商铺是否存在
if(shop == null){
// 6. 不存在, 返回404
return Result.fail("商铺不存在");
}
// 7. 存在, 将商铺数据写入Redis并返回
stringRedisTemplate.opsForValue().set(shopKey, JSON.toJSONString(shop));
return Result.ok(shop);
}
public Result queryTypeList() {
String shopTypeKey = CACHE_SHOP_TYPE_KEY;
// 1. 从Redis查询商户类型缓存
String shopTypeJson = stringRedisTemplate.opsForValue().get(shopTypeKey);
// 2. 判断缓存是否命中
if(StringUtils.isNotBlank(shopTypeJson)){
// 3. 命中, 返回商户类型
List<ShopType> shopTypes = JSON.parseArray(shopTypeJson, ShopType.class);
return Result.ok(shopTypes);
}
// 4. 未命中, 从数据库查询商户类型
List<ShopType> shopTypes = query().orderByAsc("sort").list();
// 5. 将商户类型数据写入Redis并返回
stringRedisTemplate.opsForValue().set(shopTypeKey, JSON.toJSONString(shopTypes));
stringRedisTemplate.expire(shopTypeKey, CACHE_SHOP_TYPE_TTL, TimeUnit.MINUTES);
return Result.ok(shopTypes);
}
@Override
public Result queryShopById(Long id) {
...
// 8. 超时剔除
stringRedisTemplate.expire(shopKey, CACHE_SHOP_TTL, TimeUnit.MINUTES);
return Result.ok(shop);
}
// 主动更新
@Override
@Transactional
public Result updateShop(Shop shop) {
Long id = shop.getId();
if(id == null){
return Result.fail("店铺id不能为空!");
}
String shopKey = CACHE_SHOP_KEY + id;
// 1. 修改数据库
updateById(shop);
// 2. 删除缓存
stringRedisTemplate.delete(shopKey);
// 3. 返回ok
return Result.ok();
}
public Result queryShopById(Long id) {
String shopKey = CACHE_SHOP_KEY + id;
// 1. 从Redis查询商铺缓存
String cacheShop = stringRedisTemplate.opsForValue().get(shopKey);
// 2. 判断缓存是否命中
if(StringUtils.isNotBlank(cacheShop)){
// 3. 命中, 返回商铺信息
Shop shop = JSON.parseObject(cacheShop, Shop.class);
return Result.ok(shop);
}
// 缓存穿透: 判断是否是空对象, 健不存在的话需要去数据库查, 键存在但是是空对象则直接返回
if(cacheShop != null){
return Result.fail("商铺不存在");
}
// 4. 未命中, 根据id查询数据库
Shop shop = getById(id);
// 5. 判断商铺是否存在
if(shop == null){
// 6. 缓存穿透, 缓存空对象
stringRedisTemplate.opsForValue().set(shopKey, "");
stringRedisTemplate.expire(shopKey, CACHE_NULL_TTL, TimeUnit.MINUTES);
return Result.fail("商铺不存在");
}
// 7. 存在, 将商铺数据写入Redis并返回
stringRedisTemplate.opsForValue().set(shopKey, JSON.toJSONString(shop));
stringRedisTemplate.expire(shopKey, CACHE_SHOP_TTL, TimeUnit.MINUTES);
return Result.ok(shop);
}
public Shop queryWithMutex(Long id){
String shopKey = CACHE_SHOP_KEY + id;
// 1. 从Redis查询商铺缓存
String cacheShop = stringRedisTemplate.opsForValue().get(shopKey);
// 2. 判断缓存是否命中
if(StringUtils.isNotBlank(cacheShop)){
// 3. 命中, 返回商铺信息
Shop shop = JSON.parseObject(cacheShop, Shop.class);
return shop;
}
// 缓存穿透: 判断是否是空对象, 健不存在的话需要去数据库查, 键存在但是是空对象则直接返回
if(cacheShop != null){
return null;
}
// 4. 未命中, 缓存重建
// 4.1 尝试获取互斥锁
String lockKey = LOCK_SHOP_KEY+id;
Shop shop = null;
try {
boolean isLock = tryLock(lockKey);
// 4.2 判断是否获取成功
if(!isLock){
// 4.3 失败, 休眠并重试
Thread.sleep(50);
return queryWithMutex(id);
}
// 4.4 获取锁, 根据id查询数据库
shop = getById(id);
// 5. 判断商铺是否存在
if(shop == null){
// 6. 缓存穿透, 缓存空对象
stringRedisTemplate.opsForValue().set(shopKey, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
return null;
}
// 7. 存在, 将商铺数据写入Redis并返回
stringRedisTemplate.opsForValue().set(shopKey, JSON.toJSONString(shop), CACHE_SHOP_TTL, TimeUnit.MINUTES);
} catch (InterruptedException e) {
throw new RuntimeException(e);
} finally {
// 8. 释放锁
unLock(lockKey);
}
// 9. 返回
return shop;
}
private boolean tryLock(String key){
Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", LOCK_SHOP_TTL, TimeUnit.SECONDS);
return Boolean.TRUE.equals(flag);
}
private void unLock(String key){
stringRedisTemplate.delete(key);
}
@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 queryShopById(Long id) {
// // 缓存穿透
// Shop shop = queryWithPassThrough(id);
// // 缓存击穿 - 互斥锁
// Shop shop = queryWithMutex(id);
// 缓存击穿 - 逻辑过期
Shop shop = queryWithLogicalExpire(id);
if(shop == null){
return Result.fail("店铺不存在!");
}
return Result.ok(shop);
}
// 缓存击穿 - 逻辑过期
public Shop queryWithLogicalExpire(Long id){
String shopKey = CACHE_SHOP_KEY + id;
// 1. 从Redis查询商铺缓存
String cacheShop = stringRedisTemplate.opsForValue().get(shopKey);
// 2. 判断缓存是否命中
if(StringUtils.isBlank(cacheShop)){
// 3. 未命中, 返回空
return null;
}
// 4. 命中, 取出商铺数据和过期时间
RedisData redisData = JSON.parseObject(cacheShop, RedisData.class);
JSONObject data = (JSONObject)redisData.getData();
Shop shop = JSON.parseObject(data.toJSONString(), Shop.class);
LocalDateTime expireTime = redisData.getExpireTime();
// 5. 判断缓存是否过期
if(expireTime.isAfter(LocalDateTime.now())){
// 6. 未过期
return shop;
}
// 7. 过期, 尝试获取互斥锁
String lockKey = LOCK_SHOP_KEY+id;
boolean isLock = tryLock(lockKey);
if(isLock){
// 8. 获取成功, 开启独立线程, 缓存数据
CACHE_REBUILD_EXECUTOR.submit(()->{
try {
// 重建缓存
saveShopToRedis(id, 20L);
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
// 释放锁
unLock(lockKey);
}
});
}
// 9. 获取失败, 返回商铺信息
return shop;
}
private boolean tryLock(String key){
Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", LOCK_SHOP_TTL, TimeUnit.SECONDS);
return Boolean.TRUE.equals(flag);
}
private void unLock(String key){
stringRedisTemplate.delete(key);
}
public void saveShopToRedis(Long id, Long expireSeconds) throws InterruptedException {
// 1. 查询商铺数据
Shop shop = getById(id);
// 1.1 模拟复杂查询
Thread.sleep(200);
// 2. 创建缓存数据
RedisData redisData = new RedisData();
redisData.setData(shop);
redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));
// 3. 将数据缓存导redis
stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY+id, JSON.toJSONString(redisData));
}
}
@Slf4j
@Component
public class CacheClient {
private final StringRedisTemplate stringRedisTemplate;
// 线程池
private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);
public CacheClient(StringRedisTemplate stringRedisTemplate){
this.stringRedisTemplate = stringRedisTemplate;
}
// 将任意java对象序列化为json并存储在string类型的key中, 并且可以设置TTL过期时间
public void set(String key, Object value, Long time, TimeUnit unit){
String valueJson = JSON.toJSONString(value);
stringRedisTemplate.opsForValue().set(key, valueJson, time, unit);
}
// 将任意Java对象序列化为json并存储在string类型的key中,并且可以设置逻辑过期时间,用于处理缓存击穿问题
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)));
String redisJson = JSON.toJSONString(redisData);
stringRedisTemplate.opsForValue().set(key, redisJson);
}
// 根据指定的key查询缓存,并反序列化为指定类型,利用缓存空值的方式解决缓存穿透问题
public <R, ID> R queryWithPassThrough(
String keyPrefix, ID id, Class<R> type, Function<ID, R> dbFallback, Long time, TimeUnit unit){
String key = keyPrefix + id;
// 1. 从Redis查询缓存
String json = stringRedisTemplate.opsForValue().get(key);
// 2. 判断缓存是否命中
if(StringUtils.isNotBlank(json)){
// 3. 命中, 返回
return JSON.parseObject(json, type);
}
// 缓存穿透: 判断是否是空对象, 健不存在的话需要去数据库查, 键存在但是是空对象则直接返回
if(json != null){
return null;
}
// 4. 未命中, 根据id查询数据库
R r = dbFallback.apply(id);
// 5. 判断数据是否存在
if(r == null){
// 6. 缓存穿透, 缓存空对象
stringRedisTemplate.opsForValue().set(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
return null;
}
// 7. 存在, 将数据写入Redis并返回
set(key, r, time, unit);
return r;
}
// 根据指定的key查询缓存,并反序列化为指定类型,需要利用逻辑过期解决缓存击穿问题
public <R, ID> R queryWithLogicalExpire(
String cachePrefix, String lockPrefix, ID id, Class<R> type, Function<ID, R> dbFallback, Long time, TimeUnit unit){
String key = cachePrefix + id;
// 1. 从Redis查询缓存
String json = stringRedisTemplate.opsForValue().get(key);
// 2. 判断缓存是否命中
if(StringUtils.isBlank(json)){
// 3. 未命中, 返回空
return null;
}
// 4. 命中, 取出数据和过期时间
RedisData redisData = JSON.parseObject(json, RedisData.class);
JSONObject data = (JSONObject)redisData.getData();
R r = JSON.parseObject(data.toJSONString(), type);
LocalDateTime expireTime = redisData.getExpireTime();
// 5. 判断缓存是否过期
if(expireTime.isAfter(LocalDateTime.now())){
// 6. 未过期
return r;
}
// 7. 过期, 尝试获取互斥锁
String lockKey = lockPrefix+id;
boolean isLock = tryLock(lockKey);
if(isLock){
// 8. 获取成功, 开启独立线程, 缓存数据
CACHE_REBUILD_EXECUTOR.submit(()->{
try {
// 查询数据库
R newR = dbFallback.apply(id);
// 写入缓存
setWithLogicalExpire(key, newR, time, unit);
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
// 释放锁
unLock(lockKey);
}
});
}
// 9. 获取失败, 返回旧信息
return r;
}
private boolean tryLock(String key){
Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", LOCK_SHOP_TTL, TimeUnit.SECONDS);
return Boolean.TRUE.equals(flag);
}
private void unLock(String key){
stringRedisTemplate.delete(key);
}
}
使用示例
public Result queryShopById(Long id) {
// 缓存穿透
// Shop shop = cacheClient.
// queryWithPassThrough(CACHE_SHOP_KEY, id, Shop.class, id2->getById(id2), CACHE_SHOP_TTL, TimeUnit.MINUTES);
// 缓存击穿 - 互斥锁
// Shop shop = queryWithMutex(id);
// 缓存击穿 - 逻辑过期
Shop shop = cacheClient.
queryWithLogicalExpire(CACHE_SHOP_KEY, LOCK_SHOP_KEY, id, Shop.class, this::getById, 20L, TimeUnit.SECONDS);
if(shop == null){
return Result.fail("店铺不存在!");
}
return Result.ok(shop);
}
黑马程序员. Redis入门到实战教程
https://gitee.com/Y_cen/redis