redis实现短信登录:https://blog.csdn.net/weixin_43994244/article/details/127518540
缓存
缓存数据存储于代码中,而代码运行在内存中,内存的读写性能远高于磁盘,缓存可以大大降低用户访问并发量带来的服务器读写压力。(速度快,好用)
实际开发中,会构筑多级缓存来使系统运行速度进一步提升,例如:本地缓存与redis中的缓存并发使用
浏览器缓存:主要是存在于浏览器端的缓存
应用层缓存:可以分为tomcat本地缓存,比如之前提到的map,或者是使用redis作为缓存
数据库缓存:在数据库中有一片空间是 buffer pool,增改查数据都会先加载到mysql的缓存中
CPU缓存:当代计算机最大的问题是 cpu性能提升了,但内存读写速度没有跟上,所以为了适应当下的情况,增加了cpu的L1,L2,L3级的缓存
缓存更新策略
业务场景:
- 低一致性需求:使用内存淘汰机制,例如店铺类型的查询缓存
- 高一致性需求:主动更新,并以超时剔除作为兜底方案,例如店铺详情查询的缓存 √
主动更新策略:
- Cache Aside Pattern:由缓存的调用者,在更新数据库的同时更新缓存
(可控性更高,一致性良好,实现难度一般) - Read/Write Through Pattern:缓存与数据库整合为一个服务,由服务来维护一致性,调用者调用该服务,无需关心缓存一致性问题。
(一致性优秀,实现复杂,开发成本高,性能一般,简化调用者开发) - Write Behind Caching Pattern:调用者值操作缓存,由其他线程异步的将缓存数据持久化到数据库,保证最终一致。 (数据库中的多次写合并为一次写(效率高),维护异步任务复杂,一致性难以保证-----一致性差,性能好,实现复杂)
操作缓存和数据库时需考虑:
1.删除缓存还是更新缓存?
- 更新缓存:每次更新数据库都更新缓存,无效写操作较多(写多读少,会产生无效更新,并且存在较大的线程安全问题)
- 删除缓存:更新数据库时让缓存失效,查询时再更新缓存 √ (访问时再更新缓存,没有无效更新,线程安全问题相对较低)
2.如何保证缓存与数据库的操作的同时成功或失效?(原子性)
- 单体系统:将缓存与数据库操作放在一个事务里
- 分布式系统:利用TCC等分布式事务方案
3.先操作缓存还是先操作数据库?(线程安全)
- 先删除缓存,再操作数据库 )安全问题概率较高)
- 先操作数据库,再删除缓存 √(可能性极低+超时时间,在满足原子性的情况下,安全问题概率较低)
最佳实践
读操作:
- 缓存命中则直接返回
- 缓存未命中则查询数据库,并写入缓存,设定超时时间
写操作:
- 先写数据库,再删除缓存
- 确保数据库与缓存操作的原子性
添加超时剔除和主动更新
代码举例:给查询商铺的缓存添加超时剔除和主动更新的策略
1.根据id查询店铺时,如果缓存未命中,则查询数据库,将数据库结果写入缓存,并设置超时时间
@Override
public Result queryById(Long id) {
//1.从reedis中查询商铺类型列表缓存
String shopJson = stringRedisTemplate.opsForValue().get("cache:shop:" + id);
//2.redis中存在,直接返回
if(StrUtil.isNotBlank(shopJson)){
Shop shop = JSONUtil.toBean(shopJson, Shop.class);
return Result.ok(shop);
}
//3.redis中不存在,根据id查询数据库
Shop shop = getById(id);
//4.数据库中不存在,返回错误
if(shop == null){
return Result.fail("店铺不存在!");
}
//5.数据库中存在,写入redis,设置过期时间
stringRedisTemplate.opsForValue().set("cache:shop:" + id,JSONUtil.toJsonStr(shop),30L, TimeUnit.MINUTES);
//6.返回
return Result.ok(shop);
}
2.根据id修改店铺时,先修改数据库,再删除缓存
@Override
@Transactional
public Result updateShop(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();
}
缓存穿透
缓存穿透是指客户端请求的数据在缓存中和数据库中都不存在,这样缓存永远不会生效,这些请求都会打到数据库,不断发起这样的请求,给数据库带来巨大压力。
解决方案:
- 缓存null值
- 布隆过滤
预防方案:
- 增加id的复杂度,避免被猜测id规律并且做好数据的基础格式校验,
- 加强用户权限校验
- 做好热点参数的限流
缓存空对象
优点:实现简单,维护方便
缺点:额外的内存消耗(缓存里缓存了很多null,设置TTL),可能造成短期的不一致
布隆过滤
优点:内存占用较少,没有多余key,缺点:实现复杂,存在误判可能
缓存空对象
代码举例:解决商品查询的缓存穿透问题—缓存空对象
@Override
public Result queryById(Long id) {
//1.从reedis中查询商铺类型列表缓存
String shopJson = stringRedisTemplate.opsForValue().get("cache:shop:" + id);
//2.redis中存在,有值,直接返回
if(StrUtil.isNotBlank(shopJson)){
Shop shop = JSONUtil.toBean(shopJson, Shop.class);
return Result.ok(shop);
}
//缓存中存在,判断命中是否是空值 ""
if(shopJson != null){
return Result.fail("店铺不存在!");
}
//3.redis中不存在,根据id查询数据库
Shop shop = getById(id);
//4.数据库中不存在,返回错误
if(shop == null){
//将空值写入redis
stringRedisTemplate.opsForValue().set("cache:shop:" + id,"",2L, TimeUnit.MINUTES);
return Result.fail("店铺不存在!");
}
//5.数据库中存在,写入redis,设置过期时间
stringRedisTemplate.opsForValue().set("cache:shop:" + id,JSONUtil.toJsonStr(shop),30L, TimeUnit.MINUTES);
//6.返回
return Result.ok(shop);
}
布隆过滤器
bitmap(位图):相当于一个以(bit)位为单位的数组,数组中每个单元只能存储二进制数0/1.
布隆过滤器作用:用于检索一个元素是否存在一个集合中。
id为1 的数据存储时,通过多个hash函数获取hash值,根据hash计算的数将数组对应位置改为1,查询数据时,使用相同hash函数获取hash值,判断对应位置是否为1,都为1,数据存在。
id为3的数据不存在,
代码参考:https://blog.csdn.net/qq_38517570/article/details/129386587
缓存雪崩
缓存雪崩是指在同一时段大量的缓存key同时失效或者Redis服务宕机,导致大量请求到达数据库,带来巨大压力。
解决方案:
- 给不同的Key的TTL添加随机值(同一时段大量的缓存key同时失效)
- 利用Redis集群提高服务的可用性(Redis服务宕机)
- 给缓存业务添加降级限流策略(提前做好容错处理,服务降级,快速失败,牺牲部分服务,保护数据库)
- 给业务添加多级缓存
缓存击穿
缓存击穿问题也叫热点Key问题,就是一个被高并发访问并且缓存重建业务较复杂的key突然失效了,无数的请求访问会在瞬间给数据库带来巨大的冲击。
常见的解决方案:
- 互斥锁(只有一个创建,其他线程等待,性能差)
优点:没有额外内存消耗,保证一致性,实现简单
缺点:线程需要等待,性能受影响,可能死锁风险 - 逻辑过期(永不过期,新线程查询新数据)
优点:线程无需等待,性能较好
缺点:不保证一致性,有额外内存消耗,实现复杂
互斥锁
根据id查询商铺信息-互斥锁解决缓存击穿问题
@Override
public Result queryById(Long id) {
Shop shop = queryWithMutex(id);
if(shop == null){
return Result.fail("店铺不存在");
}
return Result.ok(shop);
}
//互斥锁解决缓存击穿问题
public Shop queryWithMutex(Long id){
//1.从reedis中查询商铺类型列表缓存
String shopJson = stringRedisTemplate.opsForValue().get("cache:shop:"+id);
//2.redis中存在,有值,直接返回
if(StrUtil.isNotBlank(shopJson)){
return JSONUtil.toBean(shopJson, Shop.class);
}
//3.缓存中存在,判断命中是否是空值 ""--解决缓存穿透
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);
}
//4.4 成功,根据id查询数据库
shop = getById(id);
// 5.不存在,返回错误
if(shop == null){
//将空值写入redis
stringRedisTemplate.opsForValue().set("cache:shop:"+id,"",2L,TimeUnit.MINUTES);
//返回错误信息
return null;
}
//6.写入redis
stringRedisTemplate.opsForValue().set("cache:shop:"+id,JSONUtil.toJsonStr(shop),30L,TimeUnit.MINUTES);
}catch (Exception e){
throw new RuntimeException(e);
}
finally {
//7.释放互斥锁
unLock(lockKey);
}
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);
}
并发测试结果:
只调用一次数据库:
逻辑过期
根据id查询商铺信息-逻辑过期解决缓存击穿问题
1.创建新的实体类,对原来代码没有侵入性
@Data
public class RedisData {
//逻辑过期时间
private LocalDateTime expireTime;
//存储数据对象(不用对之前对象修改)
private Object data;
}
2.利用单元测试模拟热点数据提前存入缓存
public void saveShop2Redis(Long id,Long expireSeconds){
//1.查询店铺数据
Shop shop = getById(id);
//2.封装逻辑过期时间
RedisData redisData = new RedisData();
redisData.setData(shop);
//当前系统时间+ s
redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));
//3.写入redis
stringRedisTemplate.opsForValue().set("cache:shop:"+id,JSONUtil.toJsonStr(redisData));
}
@Test
void saveShop(){
shopService.saveShop2Redis(1L,10L);
}
3.业务代码
//线程池
private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);
public Shop queryWithLogicalExpir(Long id){
//1.从reedis中查询商铺类型列表缓存
String shopJson = stringRedisTemplate.opsForValue().get("cache:shop:"+id);
//2.redis中不存在,直接返回
if(StrUtil.isBlank(shopJson)){
return null;
}
//3.redis中存在,判断缓存是否过期
//把json反序列化为对象
RedisData redisData = JSONUtil.toBean(shopJson, RedisData.class);
Shop shop = JSONUtil.toBean((JSONObject)redisData.getData(), Shop.class);
LocalDateTime expireTime = redisData.getExpireTime();
if(expireTime.isAfter(LocalDateTime.now())){
//4.未过期,直接返回店铺信息
return shop;
}
//5.已过期,需要缓存重建
//5.1获取互斥锁
String lockKey = "lock:shop:" + id;
if(tryLock(lockKey)){
//5.2成功,开启独立线程,实现缓存重建
//线程池
CACHE_REBUILD_EXECUTOR.submit(()->{
try {
this.saveShop2Redis(id,20L);
} catch (Exception e) {
e.printStackTrace();
}finally {
//释放锁
unLock(lockKey);
}
});
}
//5.3获取失败,返回过期的店铺信息
return shop;
}
封装Redis工具类
@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){
stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value),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)));
stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData),time,unit);
}
/**
*根据指定的key查询缓存,并反序列化为指定类型,利用缓存空值的方式解决缓存穿透问题
* @param keyPrefix redis的key前缀
* @param id 传入参数id
* @param type 类结构
* @param dbFallBack 数据库查询逻辑
* @param <R> 泛型
* @param <ID> 泛型
* Function<ID,R> <ID>参数类型,R返回值类型
* @return
*/
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.从reedis中查询商铺类型列表缓存
String json = stringRedisTemplate.opsForValue().get(key + id);
//2.redis中存在,有值,直接返回
if(StrUtil.isNotBlank(json)){
return JSONUtil.toBean(json,type);
}
//缓存中存在,判断命中是否是空值 ""
if(json != null){
return null;
}
//3业务逻辑,需要调用者传数据库查询逻辑(有参有返回值的函数)
R r = dbFallBack.apply(id);
//4.数据库中不存在,返回错误
if(r == null){
//将空值写入redis
stringRedisTemplate.opsForValue().set(key," ",2L, TimeUnit.MINUTES);
return null;
}
//5.数据库中存在,写入redis,设置过期时间
this.set(key,r,time,unit);
//6.返回
return r;
}
/**
* 根据指定的key查询缓存,并反序列化为指定类型,需要利用逻辑过期解决缓存击穿问题
*/
public <ID,R> R queryWithLogicalExpire(String keyPrefix, ID id, Class<R> type, Function<ID,R> dbFallBack, Long time, TimeUnit unit){
String key = keyPrefix+id;
//1.从reedis中查询商铺类型列表缓存
String json = stringRedisTemplate.opsForValue().get(key);
//2.redis中不存在,直接返回
if(StrUtil.isBlank(json)){
return null;
}
//3.redis中存在,判断缓存是否过期
//把json反序列化为对象
RedisData redisData = JSONUtil.toBean(json, RedisData.class);
R r = JSONUtil.toBean((JSONObject)redisData.getData(), type);
LocalDateTime expireTime = redisData.getExpireTime();
if(expireTime.isAfter(LocalDateTime.now())){
//4.未过期,直接返回店铺信息
return r;
}
//5.已过期,需要缓存重建
//5.1获取互斥锁
String lockKey = "lock:shop:" + id;
if(tryLock(lockKey)){
//5.2成功,开启独立线程,实现缓存重建
//线程池
CACHE_REBUILD_EXECUTOR.submit(()->{
try {
// 查询数据库
R r1 = dbFallBack.apply(id);
// 重建缓存
this.setWithLogicalExpire(key,r1,time,unit);
} catch (Exception e) {
e.printStackTrace();
}finally {
//释放锁
unLock(lockKey);
}
});
}
//5.3获取失败,返回过期的店铺信息
return r;
}
/**
*互斥锁解决缓存击穿
*/
public <ID,R> R queryWithMutex(String keyPrefix, ID id, Class<R> type, Function<ID,R> dbFallBack, Long time, TimeUnit unit){
String key = keyPrefix+id;
//1.从reedis中查询商铺类型列表缓存
String json = stringRedisTemplate.opsForValue().get(key);
//2.redis中存在,有值,直接返回
if(StrUtil.isNotBlank(json)){
return JSONUtil.toBean(json, type);
}
//3.缓存中存在,判断命中是否是空值 ""--解决缓存穿透
if(json != null){
return null;
}
//4.实现缓存重建
//4.1.获取互斥锁
String lockKey = "lock:shop:" + id;
R r= null;
try {
boolean isLock = tryLock(lockKey);
// 4.2 判断否获取成功
if(!isLock){
//4.3 失败,则休眠重试
Thread.sleep(50);
return queryWithMutex(keyPrefix,id,type,dbFallBack,time,unit);
}
//4.4 成功,根据id查询数据库
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,unit);
}catch (Exception e){
throw new RuntimeException(e);
}
finally {
//7.释放互斥锁
unLock(lockKey);
}
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);
}
}
在ShopServiceImpl 中:
@Override
public Result queryById(Long id) {
//解决缓存穿透
Shop shop = cacheClient.queryWithPassThrough("cache:shop:", id, Shop.class, this::getById, 30L, TimeUnit.MINUTES);
//解决缓存击穿
//Shop shop = cacheClient.queryWithLogicalExpire("cache:shop:", id, Shop.class, this::getById, 30L, TimeUnit.MINUTES);
//互斥锁解决缓存击穿
//Shop shop = cacheClient.queryWithMutex("cache:shop:", id, Shop.class, this::getById, 30L, TimeUnit.MINUTES);
if(shop == null){
return Result.fail("店铺不存在");
}
return Result.ok(shop);
}