当前位置:网站首页>Redis CacheClient
Redis CacheClient
2022-06-27 14:22:00 【收心】
此工具解决了Redis的缓存击穿、缓存穿透、缓存雪崩的问题,更多的可参考泛型与Function的使用!非常好的一种方式!
注意,下方代码依赖了Hutool工具包,以及引用了几个字符常量,自行换成任意字符即可!
介绍:
缓存击穿 queryWithPassThrough
缓存穿透 queryWithMutex
缓存雪崩 queryWithLogicalExpireimport 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 java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
@Slf4j
@Component // 注册为IOC容器的Bean,使用直接Autowired
public class CacheClient {
private final StringRedisTemplate stringRedisTemplate;
// 定义一个线程池,方便开启线程去执行操作
private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);
public CacheClient(StringRedisTemplate stringRedisTemplate) {
this.stringRedisTemplate = stringRedisTemplate;
}
// 添加一个String类型的键值对
public void set(String key, Object value, Long time, TimeUnit unit) {
stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value), time, unit);
}
// 设置逻辑过期Key,以实现避免缓存击穿
public void setWithLogicalExpire(String key, Object value, Long time, TimeUnit unit) {
// 设置逻辑过期
HashMap<String, Object> hashMap = new HashMap();
hashMap.put("data", value);
hashMap.put("expireTime", LocalDateTime.now().plusSeconds(unit.toSeconds(time)));
// 写入Redis
stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(hashMap));
/**
RedisData redisData = new RedisData();
//redisData.setData(value);
//redisData.setExpireTime();
// 写入Redis
stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData));
**/
}
// 缓存穿透解决方案:正常查询,正常走。如果DB没有数据,则插入带有TTL的空值
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 (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, "", 5, TimeUnit.MINUTES);
// 返回错误信息
return null;
}
// 6.存在,写入redis
this.set(key, r, time, unit);
return r;
}
// 缓存雪崩的解决方案:询逻辑过期,如果过期了,那就重新插入进去
public <R, ID> R queryWithLogicalExpire(
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 (StrUtil.isBlank(json)) {
// 3.存在,直接返回
return null;
}
// 4.命中,需要先把json反序列化为对象
HashMap<String,Object> hashMap = JSONUtil.toBean(json, HashMap.class);
R r = JSONUtil.toBean((JSONObject) hashMap.get("data"), type);
/**
RedisData redisData = JSONUtil.toBean(json, RedisData.class);
R r = JSONUtil.toBean((JSONObject) redisData.getData(), type);
LocalDateTime expireTime = redisData.getExpireTime();
**/
LocalDateTime localDateTime = LocalDateTime.parse((CharSequence) hashMap.get("expireTime"), DateTimeFormatter.ofPattern("yyyy-MM-dd E HH:mm:ss"));
// 5.判断是否过期,使用的是纯JDK的工具
if (localDateTime.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) {
// 6.3.成功,开启独立线程,实现缓存重建
CACHE_REBUILD_EXECUTOR.submit(() -> {
try {
// 查询数据库
R newR = dbFallback.apply(id);
// 重建缓存
this.setWithLogicalExpire(key, newR, time, unit);
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
// 释放锁
unlock(lockKey);
}
});
}
// 6.4.返回过期的商铺信息
return r;
}
// 缓存雪崩解决方案:互斥锁:自己会调用自己,如果Key不存在,则只有一个线程执行插入DB操作
public <R, ID> R queryWithMutex(
String keyPrefix, ID id, Class<R> type, Function<ID, R> dbFallback, Long time, TimeUnit unit) {
String key = keyPrefix + id;
// 1.从redis查询商铺缓存
String shopJson = stringRedisTemplate.opsForValue().get(key);
// 2.判断是否存在
if (StrUtil.isNotBlank(shopJson)) {
// 3.存在,直接返回
return JSONUtil.toBean(shopJson, type);
}
// 判断命中的是否是空值
if (shopJson != null) {
// 返回一个错误信息
return null;
}
// 4.实现缓存重建
// 4.1.获取互斥锁
String lockKey = "Operate:AddLock" + 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, "", 5, TimeUnit.MINUTES);
// 返回错误信息
return null;
}
// 6.存在,写入redis
this.set(key, r, time, unit);
} catch (InterruptedException e) {
throw new RuntimeException(e);
} finally {
// 7.释放锁
unlock(lockKey);
}
// 8.返回
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);
}
}特殊说明: 以上文章,均是我实际操作,写出来的笔记资料,不会盗用别人文章!烦请各位,请勿直接盗用!转载记得标注来源!
边栏推荐
- 现在开户有优惠吗?网上开户是否安全么?
- [OS command injection] common OS command execution functions and OS command injection utilization examples and range experiments - based on DVWA range
- Too many requests at once, and the database is in danger
- Interpretation of new version features of PostgreSQL 15 (including live Q & A and PPT data summary)
- Pri3d: a representation learning method for 3D scene perception using inherent attributes of rgb-d data
- ERROR L104: MULTIPLE PUBLIC DEFINITIONS
- American chips are hit hard again, and another chip enterprise after Intel will be overtaken by Chinese chips
- CV领域一代宗师黄煦涛教授86岁冥诞,UIUC专设博士奖学金激励新锐
- [xman2018 qualifying] pass
- AQS抽象队列同步器
猜你喜欢

Leetcode 724. Find the central subscript of the array (yes, once)

SFINAE

Array related knowledge
![[OS command injection] common OS command execution functions and OS command injection utilization examples and range experiments - based on DVWA range](/img/f2/458770fc74971bef23f96f87733ee5.png)
[OS command injection] common OS command execution functions and OS command injection utilization examples and range experiments - based on DVWA range
![[xman2018 qualifying] pass](/img/eb/7bf04941a96e9522e2b93859266cf2.png)
[xman2018 qualifying] pass

Design and implementation of reading app based on Web Platform
![[business security-02] business data security test and example of commodity order quantity tampering](/img/0f/c4d4dd72bed206bbe3e15e32456e2c.png)
[business security-02] business data security test and example of commodity order quantity tampering

Redis 主从复制、哨兵模式、Cluster集群

Pycharm安装与设置

反射学习总结
随机推荐
初识云原生安全:云时代的最佳保障
【mysql进阶】MTS主从同步原理及实操指南(七)
Pytoch learning 2 (CNN)
What if the win system cannot complete the update and is revoking the status change
PCL Library - error reporting solution: cmake and Anaconda conflicts during installation
注解学习总结
Bidding announcement: Oracle database maintenance service procurement of the First Affiliated Hospital of Jinan University
Principle Comparison and analysis of mechanical hard disk and SSD solid state disk
Resolve activity startup - lifecycle Perspective
Use GCC to generate an abstract syntax tree "ast" and dump it to Dot file and visualization
Pycharm安装与设置
解析Activity启动-生命周期角度
清华&商汤&上海AI&CUHK提出Siamese Image Modeling,兼具linear probing和密集预测性能!...
Interpretation of new version features of PostgreSQL 15 (including live Q & A and PPT data summary)
Practice of constructing ten billion relationship knowledge map based on Nebula graph
R language objects are stored in JSON
Buuctf Misc
優雅的自定義 ThreadPoolExecutor 線程池
SFINAE
简析国内外电商的区别