使用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应用中实现自定义缓存有所帮助。
热门推荐
锈湖旅馆第五章猪先生怎么通关
芝士怎么做才能拉丝(芝士怎么做才能拉丝长)
看完就懂了,跳绳后拉伸动作怎么做?
梦见丢钱的深层含义
1人民币≈1千万亿津巴布韦币,了解津巴布韦币的汇率变化
人民币换津巴布韦:担心的风险及应对策略
如何编写高效的接口测试用例:技巧与最佳实践
全国土壤“大摸底”:湖南共有450多个土种,红壤、水稻土占比最大
英文口音矫正靠这招!掌握句子节奏,轻松讲出自然流畅的英文
刘鑫:以融媒体技术创新,重塑文化IP传播新范式
来自工业界的开源知识库 RAG 项目最全细节对比
古代怎么买房,大唐长安城的房价有多贵,诗人白居易五十岁才买房
沙特:“石油王国”经济多元化势成
如何浇水才能让兰花长得快开花多?
农村自建房全过程指南,从选址到入住,一步步解析建房子步骤
苯磺酸氨氯地平片:10问10答
都是「拍片子」,DR、CT、MRI 有何区别?
国际专家共识:维生素D的功能、缺乏与补充
包拯、狄仁杰与宋慈:谁才是真正的神探?
包拯、狄仁杰与宋慈:谁才是真正的神探?
十大城市通勤调查:平均40分钟左右,沪京近1小时居首
杭州楚妃巷:一条藏着美人传说的古巷
苏美尔人是否存在,苏美尔文明真的吗?
合肥李鸿章故居,历史悠久,布局严谨,探秘晚清名臣的一生荣辱
歇后语解析:武大郎跳舞——抱粗腿
社会保险监督的重要性与实施策略探讨
《黎明杀机》画面设置及性能优化指南
艺术的起源是法术,原始人那里,艺术是吞噬宇宙的吸星大法
从"无为而无不为"到"通而无为"——《淮南子》对老子无为思想的传承和引申
“胆固醇大户”被揪出,不想血脂升高,少吃这些食物