使用Spring Boot和自定义缓存注解优化应用性能
创作时间:
作者:
@小白创作中心
使用Spring Boot和自定义缓存注解优化应用性能
引用
CSDN
1.
https://blog.csdn.net/qq_21299835/article/details/140237793
在现代应用开发中,缓存是提高系统性能和响应速度的关键技术之一。Spring Boot提供了强大的缓存支持,但有时我们需要更灵活的缓存控制。本文将介绍如何使用Spring Boot和自定义缓存注解来优化应用性能。
为什么需要自定义缓存注解?
Spring Boot提供了@Cacheable、@CachePut和@CacheEvict等注解来管理缓存,但有时这些注解可能无法满足特定需求。例如,你可能需要更细粒度的缓存控制,或者希望在缓存中存储自定义数据结构。这时,自定义缓存注解就显得尤为重要。
创建自定义缓存注解
首先,我们需要创建一个自定义的缓存注解。这个注解将允许我们指定缓存的键和过期时间。
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface CustomCacheable {
/**
* 缓存名称
* @return
*/
String key() default "";
/**
* 缓存条件
* @return
*/
String condition() default "";
/**
* 过期时间,单位秒
*/
long expireTime() default 0;
}
创建缓存切面
接下来,我们需要创建一个切面来处理自定义缓存注解。这个切面将拦截带有自定义缓存注解的方法,并根据注解的参数进行缓存操作。
@Aspect
@Component
public class CustomCacheAspect {
@Resource
private RedisTemplate<String, Object> redisTemplate;
@Around("@annotation(customCacheable)")
public Object cache(ProceedingJoinPoint joinPoint, CustomCacheable customCacheable) throws Throwable {
String key = customCacheable.key();
long expireTime = customCacheable.expireTime();
//获取方法名及参数值
String methodName = joinPoint.getSignature().getName();
Object[] args = joinPoint.getArgs();
// 构建缓存键
key = key + ":" + methodName;
if (args != null && args.length > 0) {
for (Object arg : args) {
key = key + ":" + arg;
}
}
//获取方法参数名
// String[] parameterNames = ((MethodSignature) joinPoint.getSignature()).getParameterNames();
// if (parameterNames != null) {
// for (int i = 0; i < parameterNames.length; i++) {
// key = key + ":" + args[i];
// }
// }
// 尝试从缓存中获取数据
Object cachedValue = redisTemplate.opsForValue().get(key);
if (cachedValue != null) {
return cachedValue;
}
// 如果缓存中没有数据,则执行方法并将结果存入缓存
Object result = joinPoint.proceed();
if(expireTime > 0){
redisTemplate.opsForValue().set(key, result, expireTime, TimeUnit.SECONDS);
}else{
redisTemplate.opsForValue().set(key, result);
}
return result;
}
}
配置RedisTemplate
为了在切面中使用RedisTemplate,我们需要进行相应的配置。
注:这里RedisConnectionFactory Bean 可不配,不过会有提示,看着不爽。
@Configuration
public class RedisConfig {
@Bean
public RedisConnectionFactory redisConnectionFactory() {
return new LettuceConnectionFactory(); // 或者使用JedisConnectionFactory等其他实现
}
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory);
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
return template;
}
}
这里使用的依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<version>2.7.0</version>
</dependency>
使用自定义缓存注解
最后,我们可以在服务类中使用自定义缓存注解,这里使用的上一篇生成的代码测试一下。
/**
* 根据id查询
*/
@GetMapping("/{id}")
@CustomCacheable(key = "user")
public UserTest getById(@PathVariable Long id) {
return userTestService.getById(id);
}
启用AOP支持
确保在你的Spring Boot应用中启用了AOP支持。你可以在application.properties中添加以下配置:
spring.aop.auto=true
或者在启动类上添加@EnableAspectJAutoProxy注解:
@SpringBootApplication
@EnableAspectJAutoProxy
public class AppStart {
public static void main(String[] args){
SpringApplication.run(AppStart.class, args);
}
}
测试
总结
通过自定义缓存注解和切面,我们可以在Spring Boot应用中实现更灵活的缓存控制。这不仅提高了应用的性能,还使得缓存管理更加便捷和高效。希望本文对你在Spring Boot应用中实现自定义缓存有所帮助。
热门推荐
糖尿病饮食管理五大秘诀,营养师教你稳住血糖
糖尿病患者的一周减糖菜单推荐
领克01车主必看:冬季保养秘籍
探秘千年文笔塔:常州文化之旅
昆明石林风景区一日游攻略:米其林推荐的“天下第一奇观”
昆明一日游打卡:翠湖到滇池的绝美路线
88岁才旦卓玛再登春晚:布达拉宫前唱响《翻身农奴把歌唱》
腾冲必打卡:热海、火山、和顺古镇
腾冲火山热海:探秘大滚锅奇观
河南:黄河岸边的城市风光,探索中原的魅力
CNC加工工艺流程详解
数控车床编程代码指令详解:G、M、T、S、F代码的功能与应用
阿普唑仑成瘾危机:如何保护心理健康?
厦门山海步道:最美自然景观推荐
辛追夫人“体检报告”出炉:健康状况如何?
燕麦控糖新吃法:缓解坐骨神经痛
你的坐姿对吗?小心坐骨神经痛找上门!
解密配音职业:五大热门就业方向
玉林牛腩粉:乡村振兴的“香饽饽”
玉林必打卡:牛巴&炒牛料,冬日暖心首选!
第二届玉林香料产业博览会:十字街里的美食盛宴
秋冬必备!柚子皮轻松缓解咳嗽和消化不良
柚子皮泡脚:助眠消肿的养生新选择
柚子皮的神奇功效你知道几个?
冬日打卡:常州中华恐龙园&南山竹海
打卡必去!常州中华恐龙园&南山竹海门票攻略
春节打卡常州三大景区:恐龙园、天目湖、淹城春秋乐园全攻略
常州必打卡:中华恐龙园VS南山竹海,一个刺激一个静谧
王者荣耀S34赛季最强打野:百里玄策、镜、云中君
《王者荣耀》职业选手教你高效打野