/**
* 根据id查询商铺信息
* @param id 商铺id
* @return 商铺详情数据
*/
@GetMapping("/{id}")
public Result queryShopById(@PathVariable("id") Long id) {
return shopService.queryById(id);
}
*/
@Service
public class ShopServiceImpl extends ServiceImpl implements IShopService {
@Resource
private StringRedisTemplate stringRedisTemplate;
@Override
public Result queryById(Long id) {
String key="cache:shop:" + id;
//1.从Redis查询缓存
String shopJson = stringRedisTemplate.opsForValue().get(key);
//2.判断是否存在
if (StrUtil.isNotBlank(shopJson)) {
//3.存在,直接返回
Shop shop = JSONUtil.toBean(shopJson, Shop.class);
return Result.ok(shop);
}
//4.不存在,根据id查询数据库
Shop shop = getById(id);
if (shop==null) {
//5.不存在,返回错误
return Result.fail("店铺不存在");
}
//6.存在,写入Redis
stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(shop));
//7.返回
return Result.ok(shop);
}
}
@RestController
@RequestMapping("/shop-type")
public class ShopTypeController {
@Resource
private IShopTypeService typeService;
@GetMapping("list")
public Result queryTypeList() {
return typeService.queryTypeList();
}
}
@Override
public Result queryTypeList() {
String key="cache:shopType";
//1.从Redis查询缓存
String shopType = stringRedisTemplate.opsForValue().get(key);
//2.判断是否存在
if (StrUtil.isNotBlank(shopType)) {
//3.存在,直接返回
List typeList = JSONUtil.toList(shopType, ShopType.class);
return Result.ok(typeList);
}
//4.不存在,查询数据库
List typeList = query().orderByAsc("sort").list();
//5.存在,写入Redis
stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(typeList));
//7.返回
return Result.ok(typeList);
}
单体系统可以通过@Transactional注解完成事务。
通常是先操作数据库,再删除缓存,出现问题的几率极小。
第一个地方,写入Redis时加上超时时间。
//6.存在,写入Redis
stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(shop),CACHE_SHOP_TTL, TimeUnit.MINUTES);
第二个地方
controller中
/**
* 更新商铺信息
* @param shop 商铺数据
* @return 无
*/
@PutMapping
public Result updateShop(@RequestBody Shop shop) {
return shopService.update(shop);
}
service中
@Override
public Result update(Shop shop) {
Long id = shop.getId();
if(id==null){
return Result.fail("店铺id不能为空");
}
//1.更新数据库
updateById(shop);
//2.删除缓存
stringRedisTemplate.delete(CACHE_SHOP_KEY+id);
return null;
}
布隆过滤器的实现不是真的存储数据,而是用某种Hash算法计算之后用二进制压缩之类的方法保存是否存在。但是,也有可能多个数据hash值相同导致错误结果。
@Override
public Result queryById(Long id) {
String key=CACHE_SHOP_KEY+ id;
//1.从Redis查询缓存
String shopJson = stringRedisTemplate.opsForValue().get(key);
//2.判断是否存在
if (StrUtil.isNotBlank(shopJson)) {
//3.存在,直接返回
Shop shop = JSONUtil.toBean(shopJson, Shop.class);
return Result.ok(shop);
}
//判断命中的是否是空值
if(shopJson!=null){
//返回一个错误信息
return Result.fail("店铺不存在");
}
//4.不存在,根据id查询数据库
Shop shop = getById(id);
if (shop==null) {
//将空值写入Redis
stringRedisTemplate.opsForValue().set(key,"",CACHE_NULL_TTL, TimeUnit.MINUTES);
//5.不存在,返回错误
return Result.fail("店铺不存在");
}
//6.存在,写入Redis
stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(shop),CACHE_SHOP_TTL, TimeUnit.MINUTES);
//7.返回
return Result.ok(shop);
}
宕机时降级限流也是用sentinel实现。
nginx缓存也是一级缓存.
tmd,一直在说springcloud里面有讲。
这里可以参考一下redisson的源码设计思路,设计一个监听通知机制!
逻辑过期解决方案不会设置ttl过期时间,而是新增一个exprie字段,从redis里面查询发现是过期数据时就需要加锁开启一个新线程去更新缓存,然后直接返回旧数据。有别的线程来获取锁失败时说明已经有线程在进行更新,所以就直接返回过期数据,避免了过多线程等待锁。
这里的锁不能用lock和synchronized进行互斥实现,这两个会一直等待.这里用到Redis的一个命令setnx, 这个是一旦设置之后就不能修改,只能删除,但是如果因为意外原因导致迟迟不能删除会有大问题,所以这里会给锁设置一个有效期.
@Service
public class ShopServiceImpl extends ServiceImpl implements IShopService {
@Resource
private StringRedisTemplate stringRedisTemplate;
@Override
public Result queryById(Long id) {
//缓存穿透
//Shop shop=queryWithPassThrouh(id);
//互斥锁解决缓存击穿
Shop shop = queryWithMutex(id);
if(shop==null){
return Result.fail("店铺不存在!");
}
//7.返回
return Result.ok(shop);
}
public Shop queryWithMutex(Long id){
String key=CACHE_SHOP_KEY+ id;
//1.从Redis查询缓存
String shopJson = stringRedisTemplate.opsForValue().get(key);
//2.判断是否存在
if (StrUtil.isNotBlank(shopJson)) {
//3.存在,直接返回
return JSONUtil.toBean(shopJson, Shop.class);
}
//判断命中的是否是空值
if(shopJson!=null){
//返回一个错误信息
return null;
}
//4.实现缓存重建
//4.1获取互斥锁
String lockkey="lock:shop:"+id;
Shop shop = null;
try {
boolean isLock = tryLock(lockkey);
//4.2判断是否获取成功
if(!isLock){
//4.3失败,休眠并重试
Thread.sleep(50);
return queryWithMutex(id); //这里有可能会出现栈溢出的情况。
}
//获取成功之后应该再次检查缓存是否存在,有可能别的线程已经重建完了缓存,所以这里就无需再重建缓存
shopJson = stringRedisTemplate.opsForValue().get(key);
//再次判断是否存在
if (StrUtil.isNotBlank(shopJson)) {
//存在,直接返回
return JSONUtil.toBean(shopJson, Shop.class);
}
//4.4根据id查询数据库
shop = getById(id);
//模拟重建的延时
Thread.sleep(200);
if (shop==null) {
//将空值写入Redis
stringRedisTemplate.opsForValue().set(key,"",CACHE_NULL_TTL, TimeUnit.MINUTES);
//5.不存在,返回错误
return shop;
}
//6.存在,写入Redis
stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(shop),CACHE_SHOP_TTL, TimeUnit.MINUTES);
} catch (InterruptedException e) {
throw new RuntimeException(e);
} finally {
//7.释放互斥锁
unlock(lockkey);
}
//8.返回
return shop;
}
public Shop queryWithPassThrouh(Long id){
String key=CACHE_SHOP_KEY+ id;
//1.从Redis查询缓存
String shopJson = stringRedisTemplate.opsForValue().get(key);
//2.判断是否存在
if (StrUtil.isNotBlank(shopJson)) {
//3.存在,直接返回
Shop shop = JSONUtil.toBean(shopJson, Shop.class);
return shop;
}
//判断命中的是否是空值
if(shopJson!=null){
//返回一个错误信息
return null;
}
//4.不存在,根据id查询数据库
Shop shop = getById(id);
if (shop==null) {
//将空值写入Redis
stringRedisTemplate.opsForValue().set(key,"",CACHE_NULL_TTL, TimeUnit.MINUTES);
//5.不存在,返回错误
return shop;
}
//6.存在,写入Redis
stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(shop),CACHE_SHOP_TTL, TimeUnit.MINUTES);
//7.返回
return shop;
}
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);
}
@Override
public Result update(Shop shop) {
Long id = shop.getId();
if(id==null){
return Result.fail("店铺id不能为空");
}
//1.更新数据库
updateById(shop);
//2.删除缓存
stringRedisTemplate.delete(CACHE_SHOP_KEY+id);
return null;
}
}
这里可以上Jmeter进行压测,上100个线程进行测试
但是最终实际只查询了一次数据库.
为了能增加一个逻辑过期时间的字段,新建一个对象
@Data
public class RedisData {
private LocalDateTime expireTime;
private Object data;
}
@Service
public class ShopServiceImpl extends ServiceImpl implements IShopService {
@Resource
private StringRedisTemplate stringRedisTemplate;
@Override
public Result queryById(Long id) {
//缓存穿透
//Shop shop=queryWithPassThrouh(id);
//互斥锁解决缓存击穿
// Shop shop = queryWithMutex(id);
//逻辑过期解决缓存击穿问题
Shop shop = queryWithLogicalExpire(id);
if(shop==null){
return Result.fail("店铺不存在!");
}
//7.返回
return Result.ok(shop);
}
private static final ExecutorService CACHE_REBUILD_EXECUTOR= Executors.newFixedThreadPool(10);
public Shop queryWithLogicalExpire(Long id){
String key=CACHE_SHOP_KEY+ id;
//1.从Redis查询缓存
String shopJson = stringRedisTemplate.opsForValue().get(key);
//2.判断是否存在
if (StrUtil.isBlank(shopJson)) {
//3.存在,直接返回null
return null;
}
//4.命中,需要先把json反序列化为对象
RedisData redisData = JSONUtil.toBean(shopJson, RedisData.class);
Shop shop = JSONUtil.toBean((JSONObject)redisData.getData(), Shop.class);
LocalDateTime expireTime = redisData.getExpireTime();
//5.判断是否过期
if(expireTime.isAfter(LocalDateTime.now())){
//5.1未过期,直接返回店铺信息
return shop;
}
//5.2已过期,需要缓存重建
//6.缓存重建
//6.1获取互斥锁
String lockKey=LOCK_SHOP_KEY+id;
boolean isLock = tryLock(lockKey);
//6.2判断是否获取锁成功
if(isLock){
//这里应该再次检测缓存是否过期,做双重判断,如果没过期就不需重建了,因为可能别的线程已经重建了
shopJson = stringRedisTemplate.opsForValue().get(key);
redisData = JSONUtil.toBean(shopJson, RedisData.class);
expireTime = redisData.getExpireTime();
if(expireTime.isAfter(LocalDateTime.now())){
//返回前先释放锁
unlock(lockKey);
//5.1未过期,直接返回店铺信息
return shop;
}
//6.3成功,开启独立线程,实现缓存重建
CACHE_REBUILD_EXECUTOR.submit(()->{
try {
//重建缓存
this.saveShop2Redis(id,20L);
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
//释放锁
unlock(lockKey);
}
});
}
//6.4失败,返回过期商铺信息。
return shop;
}
public Shop queryWithMutex(Long id){
String key=CACHE_SHOP_KEY+ id;
//1.从Redis查询缓存
String shopJson = stringRedisTemplate.opsForValue().get(key);
//2.判断是否存在
if (StrUtil.isNotBlank(shopJson)) {
//3.存在,直接返回
return JSONUtil.toBean(shopJson, Shop.class);
}
//判断命中的是否是空值
if(shopJson!=null){
//返回一个错误信息
return null;
}
//4.实现缓存重建
//4.1获取互斥锁
String lockkey="lock:shop:"+id;
Shop shop = null;
try {
boolean isLock = tryLock(lockkey);
//4.2判断是否获取成功
if(!isLock){
//4.3失败,休眠并重试
Thread.sleep(50);
return queryWithMutex(id); //这里有可能会出现栈溢出的情况。
}
//获取成功之后应该再次检查缓存是否存在,有可能别的线程已经重建完了缓存,所以这里就无需再重建缓存
shopJson = stringRedisTemplate.opsForValue().get(key);
//再次判断是否存在
if (StrUtil.isNotBlank(shopJson)) {
//存在,直接返回
return JSONUtil.toBean(shopJson, Shop.class);
}
//4.4根据id查询数据库
shop = getById(id);
//模拟重建的延时
//Thread.sleep(200);
if (shop==null) {
//将空值写入Redis
stringRedisTemplate.opsForValue().set(key,"",CACHE_NULL_TTL, TimeUnit.MINUTES);
//5.不存在,返回错误
return shop;
}
//6.存在,写入Redis
stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(shop),CACHE_SHOP_TTL, TimeUnit.MINUTES);
} catch (InterruptedException e) {
throw new RuntimeException(e);
} finally {
//7.释放互斥锁
unlock(lockkey);
}
//8.返回
return shop;
}
public Shop queryWithPassThrouh(Long id){
String key=CACHE_SHOP_KEY+ id;
//1.从Redis查询缓存
String shopJson = stringRedisTemplate.opsForValue().get(key);
//2.判断是否存在
if (StrUtil.isNotBlank(shopJson)) {
//3.存在,直接返回
Shop shop = JSONUtil.toBean(shopJson, Shop.class);
return shop;
}
//判断命中的是否是空值
if(shopJson!=null){
//返回一个错误信息
return null;
}
//4.不存在,根据id查询数据库
Shop shop = getById(id);
if (shop==null) {
//将空值写入Redis
stringRedisTemplate.opsForValue().set(key,"",CACHE_NULL_TTL, TimeUnit.MINUTES);
//5.不存在,返回错误
return shop;
}
//6.存在,写入Redis
stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(shop),CACHE_SHOP_TTL, TimeUnit.MINUTES);
//7.返回
return shop;
}
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);
}
public void saveShop2Redis(Long id,Long expireSeconds) throws InterruptedException {
//1.查询店铺数据
Shop shop = getById(id);
//模拟延时
// 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,JSONUtil.toJsonStr(redisData));
}
@Override
public Result update(Shop shop) {
Long id = shop.getId();
if(id==null){
return Result.fail("店铺id不能为空");
}
//1.更新数据库
updateById(shop);
//2.删除缓存
stringRedisTemplate.delete(CACHE_SHOP_KEY+id);
return null;
}
}
@Data
public class RedisData {
private LocalDateTime expireTime;
private Object data;
}
@Slf4j
@Component
public class CacheClient {
@Resource
private StringRedisTemplate stringRedisTemplate;
String LOCK_SHOP_KEY="lock:shop:";
public CacheClient(StringRedisTemplate stringRedisTemplate) {
this.stringRedisTemplate = stringRedisTemplate;
}
public void set(String key, Object value, Long time, TimeUnit timeUnit){
stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value),time,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)));
//写入Redis
stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData));
}
public R queryWithPassThrough(
String keyPrefix, ID id, Class type, FunctiondbFallback, Long time, TimeUnit timeUnit){
String key=keyPrefix+id;
//1.从Redis查询缓存
String json = stringRedisTemplate.opsForValue().get(key);
//2.判断是否存在
if (StrUtil.isNotBlank(json)) {
//3.存在,直接返回
return JSONUtil.toBean(json, type);
}
//判断命中的是否是空值
if(json!=null){
//返回一个错误信息
return null;
}
//4.不存在,根据id查询数据库
R r=dbFallback.apply(id);
//5.不存在,返回错误
if (r==null) {
//将空值写入Redis
stringRedisTemplate.opsForValue().set(key,"",2L, TimeUnit.MINUTES);
return null;
}
//6.存在,写入Redis
this.set(key,r,time,timeUnit);
//7.返回
return r;
}
private static final ExecutorService CACHE_REBUILD_EXECUTOR= Executors.newFixedThreadPool(10);
public R queryWithLogicalExpire(
String keyPrefix, ID id, Class type, FunctiondbFallback, Long time, TimeUnit timeUnit){
String key=keyPrefix+ id;
//1.从Redis查询缓存
String json = stringRedisTemplate.opsForValue().get(key);
//2.判断是否存在
if (StrUtil.isBlank(json)) {
//3.存在,直接返回null
return null;
}
//4.命中,需要先把json反序列化为对象
RedisData redisData = JSONUtil.toBean(json, RedisData.class);
R r = JSONUtil.toBean((JSONObject)redisData.getData(), 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;
boolean isLock = tryLock(lockKey);
//6.2判断是否获取锁成功
if(isLock){
//这里应该再次检测缓存是否过期,做双重判断,如果没过期就不需重建了,因为可能别的线程已经重建了
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())){
//返回前先释放锁
unlock(lockKey);
//5.1未过期,直接返回店铺信息
return r;
}
//6.3成功,开启独立线程,实现缓存重建
CACHE_REBUILD_EXECUTOR.submit(()->{
try {
//重建缓存
//查询数据库
R r1 = dbFallback.apply(id);
//写入Redis
this.setWithLogicalExpire(key,r1,time,timeUnit);
} 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 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);
//逻辑过期解决缓存击穿问题
// Shop shop = cacheClient
// .queryWithLogicalExpire(CACHE_SHOP_KEY,id,Shop.class,this::getById,CACHE_SHOP_TTL,TimeUnit.SECONDS);
if(shop==null){
return Result.fail("店铺不存在!");
}
//7.返回
return Result.ok(shop);
}
@Override
public Result update(Shop shop) {
Long id = shop.getId();
if(id==null){
return Result.fail("店铺id不能为空");
}
//1.更新数据库
updateById(shop);
//2.删除缓存
stringRedisTemplate.delete(CACHE_SHOP_KEY+id);
return null;
}
}
去看文档资料里面xmind文档,那个里面总结的很好。