Spring声明式基于注解的缓存(2-实践篇)

简介: 目录一、序言二、使用示例1、配置(1) application.properties(2) 基于Redis缓存的CacheManager配置2、注解运用测试用例(1) 指定key条件式缓存(2) 返回值为Optional类型条件式缓存(3) 不指定key条件式缓存(4) 指定key删除缓存(5) 指定key更新缓存三、结语

目录

一、序言

二、使用示例

1、配置

(1) application.properties

(2) 基于Redis缓存的CacheManager配置

2、注解运用测试用例

(1) 指定key条件式缓存

(2) 返回值为Optional类型条件式缓存

(3) 不指定key条件式缓存

(4) 指定key删除缓存

(5) 指定key更新缓存

三、结语

一、序言


在前面 Spring声明式基于注解的缓存(1-理论篇)一节中我们大致介绍了基于注解的缓存抽象相关理论知识,包括常用注解@Cacheable、@CachePut、@CacheEvict、@Caching和@CacheConfig,还有缓存相关组件CacheManager和CacheResolver的作用。


这篇是实战环节,主要会包含缓存相关注解的应用。

二、使用示例


1、配置

(1) application.properties

spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.password=lyl
spring.redis.database=0
spring.redis.timeout=1000ms
spring.redis.lettuce.pool.min-idle=0
spring.redis.lettuce.pool.max-idle=8
spring.redis.lettuce.pool.max-active=50
spring.redis.lettuce.pool.max-wait=1000ms
spring.redis.lettuce.pool.time-between-eviction-runs=30000ms


(2) 基于Redis缓存的CacheManager配置

@EnableCaching
@Configuration
public class RedisCacheConfig {
  private static final String KEY_SEPERATOR = ":";
  /**
   * 自定义CacheManager,具体配置参考{@link org.springframework.boot.autoconfigure.cache.RedisCacheConfiguration}
   * @param redisConnectionFactory 自动配置会注入
   * @return
   */
  @Bean(name = "redisCacheManager")
  public RedisCacheManager redisCacheManager(RedisConnectionFactory redisConnectionFactory) {
    RedisSerializer<String> keySerializer = new StringRedisSerializer();
    RedisSerializer<Object> valueSerializer = new GenericJackson2JsonRedisSerializer();
    RedisCacheConfiguration cacheConfig = RedisCacheConfiguration.defaultCacheConfig()
      .serializeKeysWith(SerializationPair.fromSerializer(keySerializer))
      .serializeValuesWith(SerializationPair.fromSerializer(valueSerializer))
      .computePrefixWith(key -> key.concat(KEY_SEPERATOR));
    return RedisCacheManager.builder(redisConnectionFactory).cacheDefaults(cacheConfig).build();
  }
}


2、注解运用测试用例

SpringCacheService定义了相关的缓存操作,如下:

@Service
@CacheConfig(cacheManager = "redisCacheManager")
public class SpringCacheService {
  /**
   * key:缓存key名称,支持SPEL
   * value:缓存名称
   * condition:满足条件可缓存才缓存结果,支持SPEL
   * unless:满足条件结果不缓存,支持SPEL
   * @param stuNo
   * @return
   */
  @Cacheable(key = "#stuNo", value = "student-cache", condition = "#stuNo gt 0", unless = "#result eq null")
  public StudentDO getStudentByNo(int stuNo) {
    StudentDO student = new StudentDO(stuNo, "liuyalou");
    System.out.println("模拟从数据库中读取:" + student);
    return student;
  }
  /**
   * 不指定key,默认会用{@link org.springframework.cache.interceptor.SimpleKeyGenerator}
   * 如果方法无参数则返回空字符串,只有一个参数则返回参数值,两个参数则返回包含两参数的SimpleKey
   * @param username
   * @param age
   * @return
   */
  @Cacheable(value = "user-cache", unless = "#result eq null")
  public UserDO getUserByUsernameAndAge(String username, int age) {
    UserDO userDo = new UserDO(username, age);
    System.out.println("模拟从数据库中读取:" + userDo);
    return userDo;
  }
  @Cacheable(key = "#stuNo + '_' +#stuName", value = "student-cache", unless = "#result?.stuName eq null")
  public Optional<StudentDO> getStudentByNoAndName(int stuNo, String stuName) {
    if (stuNo <= 0) {
      return Optional.empty();
    }
    StudentDO student = new StudentDO(stuNo, stuName);
    System.out.println("模拟从数据库中读取:" + student);
    return Optional.ofNullable(student);
  }
  @CacheEvict(value = "student-cache", key = "#stuNo")
  public void removeStudentByStudNo(int stuNo) {
    System.out.println("从数据库删除数据,key为" + stuNo + "的缓存将会被删");
  }
  @CachePut(value = "student-cache", key = "#student.stuNo", condition = "#result ne null")
  public StudentDO updateStudent(StudentDO student) {
    System.out.println("数据库进行了更新,检查缓存是否一致");
    return student;
  }
}

1) 指定key条件式缓存

这里我们定义了名为student-cache,key为1的缓存,以及是否缓存的两个条件:

  • 如果stuNo小于0则不缓存。
  • 如果方法执行结果不为空才缓存。
/**
   * key:缓存key名称,支持SPEL
   * value:缓存名称
   * condition:满足条件可缓存才缓存结果,支持SPEL
   * unless:满足条件结果不缓存,支持SPEL
   * @param stuNo
   * @return
   */
  @Cacheable(key = "#stuNo", value = "student-cache", condition = "#stuNo gt 0", unless = "#result eq null")
  public StudentDO getStudentByNo(int stuNo) {
    StudentDO student = new StudentDO(stuNo, "liuyalou");
    System.out.println("模拟从数据库中读取:" + student);
    return student;
  }


  @Test
  public void getStudentByNo() {
    StudentDO studentDo = springCacheService.getStudentByNo(1);
    System.out.println(studentDo);
  }

控制台输出如下,如果Redis中没有该student-cache:1对应的值,则会执行方法体的代码。

模拟从数据库中读取:StudentDO[stuName=liuyalou,stuNo=1]
程序执行结果为: StudentDO[stuName=liuyalou,stuNo=1]

该方法执行后,让我们看看Redis中的key,可以看到多了student-cache:1的缓存键值对信息。b6e6ed10ee8c4f77b3b310a1f71feff9.png备注:当再次执行该方法时,不会执行方法体逻辑,而是从Redis中获取对应缓存key的值。

(2) 返回值为Optional类型条件式缓存

这里我们自定义了名为student-cache,key为stuNo_stuName的缓存,方法返回参数为Optional类型。如果Optional的值为空,则方法的执行结果不会被缓存。

  @Cacheable(key = "#stuNo + '_' +#stuName", value = "student-cache", unless = "#result?.stuName eq null")
  public Optional<StudentDO> getStudentByNoAndName(int stuNo, String stuName) {
    if (stuNo <= 0) {
      return Optional.empty();
    }
    StudentDO student = new StudentDO(stuNo, stuName);
    System.out.println("模拟从数据库中读取:" + student);
    return Optional.ofNullable(student);
  }
  @Test
  public void getStudentByNoAndName() {
    Optional<StudentDO> studentDo = springCacheService.getStudentByNoAndName(1, "Nick");
    System.out.println("程序执行结果为: " + studentDo.orElse(null));
  }


备注:#result指向的不是Optional实例,而是Student实例,因为Optional中的值可能为null,这里我们用了安全导航操作符?

控制台输出:

模拟从数据库中读取:StudentDO[stuName=Nick,stuNo=1]
程序执行结果为: StudentDO[stuName=Nick,stuNo=1]


f3a1e2118dae42b0b0fbf93157885ef7.png

(3) 不指定key条件式缓存

下面的方法我们没有指定key属性,key的生成会用默认的key生成器SimpleKeyGenerator来生成。

@Cacheable(value = "user-cache", unless = "#result eq null")
  public UserDO getUserByUsernameAndAge(String username, int age) {
    UserDO userDo = new UserDO(username, age);
    System.out.println("模拟从数据库中读取:" + userDo);
    return userDo;
  }
@Test
  public void getUserByUsernameAndAge() {
    UserDO userDo = springCacheService.getUserByUsernameAndAge("liuyalou", 23);
    System.out.println("程序执行结果为: " + userDo);
  }

314f501cae0e49749f4d37178362d68c.png备注:可以看到SimpleKeyGernerator生成的key名是根据对象属性来生成的。

(4) 指定key删除缓存

这个注解我们用来根据指定缓存key来清除缓存。

  @CacheEvict(value = "student-cache", key = "#stuNo")
  public void removeStudentByStudNo(int stuNo) {
    System.out.println("从数据库删除数据,key为" + stuNo + "的缓存将会被删");
  }
  @Test
  public void getStudentByNo() {
    StudentDO studentDo = springCacheService.getStudentByNo(1);
    System.out.println("程序执行结果为: " + studentDo);
  }
  @Test
  public void removeStudentByStudNo() {
    springCacheService.removeStudentByStudNo(1);
  }

我们先执行getStudentByNo测试用例,再执行removeStudentByStudNo,控制台输出如下:

模拟从数据库中读取:StudentDO[stuName=liuyalou,stuNo=1]
程序执行结果为: StudentDO[stuName=liuyalou,stuNo=1]
从数据库删除数据,key为1的缓存将会被删

备注:执行完后可以看到Redis中的key会被删除。

(5) 指定key更新缓存

接下来我们根据指定key更新缓存,这里我们也指定了缓存条件,只有当缓存结果不为空时才缓存

  @CachePut(value = "student-cache", key = "#student.stuNo", unless = "#result eq null”)
  public StudentDO updateStudent(StudentDO student) {
    System.out.println("数据库进行了更新,检查缓存是否一致");
    return student;
  }


  @Test
  public void updateStudent() {
    StudentDO oldStudent = springCacheService.getStudentByNo(1);
    System.out.println("原缓存内容为:" + oldStudent);
    springCacheService.updateStudent(new StudentDO(1, "Evy"));
    StudentDO newStudent = springCacheService.getStudentByNo(1);
    System.out.println("更新后缓存内容为:" + newStudent);
  }


控制台输出为:

原缓存内容为:StudentDO[stuName=Evy,stuNo=1]
数据库进行了更新,检查缓存是否一致
更新后缓存内容为:StudentDO[stuName=Evy,stuNo=1]


最终Redis中的key信息如下7603062adb154d29859b866894d39270.png

三、结语


总得来说,声明式缓存抽象和声明式事务一样,使用起来都比较简单。更多的细节描述可以参考:Spring缓存抽象官方文档

有同学可能会发现,Spring提供的这些注解不支持过期时间的设置,官方文档也有一些解释,如下:66e0efe046ae4bb4a18f59cce5b6766b.png官方提供的建议是通过缓存提供器来实现,其实就是我们可以通过自定义CacheManager来实现。缓存抽象只是一种逻辑抽象,而不是具体的缓存实现,具体怎么写缓存,缓存写到哪里应该由缓存管理器来实现。


下一节我们会通过自定义CacheResolver、RedisCacheManager、以及相关Cache注解来实现带过期时间的缓存实现。


相关文章
|
7月前
|
存储 人工智能 Java
AI 超级智能体全栈项目阶段四:学术分析 AI 项目 RAG 落地指南:基于 Spring AI 的本地与阿里云知识库实践
本文介绍RAG(检索增强生成)技术,结合Spring AI与本地及云知识库实现学术分析AI应用,利用阿里云Qwen-Plus模型提升回答准确性与可信度。
2085 90
AI 超级智能体全栈项目阶段四:学术分析 AI 项目 RAG 落地指南:基于 Spring AI 的本地与阿里云知识库实践
|
8月前
|
缓存 监控 Java
SpringBoot @Scheduled 注解详解
使用`@Scheduled`注解实现方法周期性执行,支持固定间隔、延迟或Cron表达式触发,基于Spring Task,适用于日志清理、数据同步等定时任务场景。需启用`@EnableScheduling`,注意线程阻塞与分布式重复问题,推荐结合`@Async`异步处理,提升任务调度效率。
1196 128
|
7月前
|
人工智能 监控 Java
Spring AI Alibaba实践|后台定时Agent
基于Spring AI Alibaba框架,可构建自主运行的AI Agent,突破传统Chat模式限制,支持定时任务、事件响应与人工协同,实现数据采集、分析到决策的自动化闭环,提升企业智能化效率。
Spring AI Alibaba实践|后台定时Agent
|
7月前
|
XML Java 应用服务中间件
【SpringBoot(一)】Spring的认知、容器功能讲解与自动装配原理的入门,带你熟悉Springboot中基本的注解使用
SpringBoot专栏开篇第一章,讲述认识SpringBoot、Bean容器功能的讲解、自动装配原理的入门,还有其他常用的Springboot注解!如果想要了解SpringBoot,那么就进来看看吧!
697 2
|
8月前
|
XML Java 数据格式
常用SpringBoot注解汇总与用法说明
这些注解的使用和组合是Spring Boot快速开发和微服务实现的基础,通过它们,可以有效地指导Spring容器进行类发现、自动装配、配置、代理和管理等核心功能。开发者应当根据项目实际需求,运用这些注解来优化代码结构和服务逻辑。
511 12
|
8月前
|
传感器 Java 数据库
探索Spring Boot的@Conditional注解的上下文配置
Spring Boot 的 `@Conditional` 注解可根据不同条件动态控制 Bean 的加载,提升应用的灵活性与可配置性。本文深入解析其用法与优势,并结合实例展示如何通过自定义条件类实现环境适配的智能配置。
412 0
探索Spring Boot的@Conditional注解的上下文配置
|
8月前
|
智能设计 Java 测试技术
Spring中最大化@Lazy注解,实现资源高效利用
本文深入探讨了 Spring 框架中的 `@Lazy` 注解,介绍了其在资源管理和性能优化中的作用。通过延迟初始化 Bean,`@Lazy` 可显著提升应用启动速度,合理利用系统资源,并增强对 Bean 生命周期的控制。文章还分析了 `@Lazy` 的工作机制、使用场景、最佳实践以及常见陷阱与解决方案,帮助开发者更高效地构建可扩展、高性能的 Spring 应用程序。
319 0
Spring中最大化@Lazy注解,实现资源高效利用
|
Java API Spring
Spring容器如何使用一个注解来指定一个类型为配置类型
Spring容器如何使用一个注解来指定一个类型为配置类型
255 0
|
XML Java 测试技术
Spring IOC—基于注解配置和管理Bean 万字详解(通俗易懂)
Spring 第三节 IOC——基于注解配置和管理Bean 万字详解!
979 26
|
Java Spring
【Spring】方法注解@Bean,配置类扫描路径
@Bean方法注解,如何在同一个类下面定义多个Bean对象,配置扫描路径
673 73

热门文章

最新文章