当前位置:网站首页>一个注解实现方法返回数据写入缓存(切面、Redis实现)
一个注解实现方法返回数据写入缓存(切面、Redis实现)
2022-07-22 06:03:00 【[email protected】
一、用法
如何使用
@CacheConfig(value = "mabo.test",timeOut = 1, TimeUnit = TimeUnit.SECONDS)
public String test(String id){
return id;
}
参数说明
底层采用redis来进行存储,用有超时时间的set方法来存储
value key值
timeOut 超时时间
TimeUnit 超时时间的单位
二、原理
采用切面的方式,对方法进行动态代理,一共分为两种情况
1、返回方法原本返回值
先去缓存中读取该方法的返回值,如果为空,则执行方法
2、返回缓存数据
不为空,直接返回缓存数据
源码
@Around("@annotation(cacheConfig)")
public Object addEventListener(ProceedingJoinPoint joinPoint, CacheConfig cacheConfig) throws Throwable {
String key = cacheConfig.value();
//返回值
Object proceed =null;
Object o = redisTemplate.opsForValue().get(key);
String declaringTypeName = joinPoint.getSignature().getDeclaringTypeName();
if (o!=null){
log.info(declaringTypeName+"方法获取缓存成功"+o);
return o;
}
else {
Object[] args = joinPoint.getArgs();
try {
proceed = joinPoint.proceed(args);
redisTemplate.opsForValue().set(key,proceed,cacheConfig.timeOut(),cacheConfig.TimeUnit());
} catch (Throwable throwable) {
log.error(declaringTypeName+"方法执行异常"+throwable);
}
return proceed;
}
}
demo下载地址
github地址
github地址
https://github.com/MaBo2420935619/Cache
国内下载地址
点击跳转国内下载地址
http://47.103.194.1:8081/download/demo?fileName=Cache.zip
版权声明
本文为[[email protected]]所创,转载请带上原文链接,感谢
https://blog.csdn.net/weixin_47053123/article/details/125921586
边栏推荐
猜你喜欢
随机推荐
Causes of server buffer/cache and buffer/cache release
How to implement Apache's built-in AB stress testing tool
Pytorch optimizer: optim SGD && optimizer.zero_ grad()
Win11开机只有鼠标显示怎么办?
Reading papers [6] autoassembly: learning augmentation strategies from data
Server network performance tuning cases
接招吧。最强“高并发”系统设计 46 连问,分分钟秒杀一众面试者
What if win11 encounters a problem and needs to restart?
GMT 0009-2012数据格式-GO语言操作
Classification of attention mechanism
UE4 enters the designated area to realize the trigger acceleration function
Enthusiasm and expertise fly together | Microsoft's most valuable expert project, attracting Microsoft technology contributors!
vivo官网APP全机型UI适配方案
UE4 combines the objects made by the brush into a whole
NFS网络文件系统
注意力机制的分类
【外部排序】快排思想完成外部排序
[pictures and texts] detailed tutorial of online one click reinstallation of win7 system
JS的DOM操作——事件代理
MySQL foundation +mysql cluster review