使用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应用中实现自定义缓存有所帮助。
热门推荐
探究刘备的身世:刘弘之子的争议与历史考证
三国正史中,真正能够以一敌百的猛将只有4位,他们分别是谁?
刘备若迎汉献帝:可能性与历史背景探析
一周涨幅近1000%!特朗普与“散户之王”联手带飞meme币
济南必吃的8种绝世美食,看看你尝过几种?
济南餐饮品牌,美食之都的繁华与魅力
心理学上有一个词叫:标签效应
最新研究发现:有这8个习惯的人,更容易长寿
决定人寿命长短的,不只是吃和运动,还有这些关键因素
喝咖啡真的会升高血压吗?最新研究给出答案
心血管专家推荐:高血压患者的咖啡饮用指南
心血管专家王医生:高血压患者如何健康饮咖啡?
退休后工作就不算“劳动者”了,劳动权益如何保障?
民办职业培训机构办学资格申请需要哪里条件才能审批?
湖南花鼓戏:元旦节庆中的文化传承与创新
沔阳花鼓戏:地域特色的传承与创新
湖南花鼓戏:在传承与创新中绽放新光彩
花鼓戏唱词的特色解析:以湖南、湖北、安徽为例
湖南花鼓戏:文化瑰宝中的独特魅力
《钢铁是怎样炼成的》第一章第二章内容概括和阅读感受
秋冬护骨新趋势:科学预防股骨再伤
股骨骨折术后康复:科学锻炼助你快速恢复!
股骨干骨折术后康复新趋势:从干细胞技术到传统训练
二甲双胍新发现:抗糖尿病还能缓解焦虑?
湖南花鼓戏:从田间地头到文旅新宠
冬日打卡:西塔大冷面,排队也要吃的美味!
红烧肉的英文表达你get了吗?
矿泉水版东北大冷面,夏日清凉必备!
解密哈尔滨烤冷面走红:从街头小吃到国民爆款
从“烧”字说起:正确烹饪保障饮食安全