boxmoe_header_banner_img

Hello! 欢迎来到悠悠畅享网!

文章导读

动态缓存键在 Spring Boot 中的应用


avatar
作者 2025年9月9日 7

动态缓存键在 Spring Boot 中的应用

本文介绍了如何在 spring Boot 应用中实现动态缓存键。通过直接操作 CacheManager 获取 Cache 对象,并使用 cache.get(key, () -> …) 方法,可以根据请求参数动态生成缓存键,从而灵活地缓存数据。虽然缓存名称保持静态,但缓存键的动态性足以满足大多数需求。

spring boot 应用中,使用 @cacheable 注解可以方便地实现缓存功能。然而,有时我们需要根据请求参数动态地生成缓存键,以更精细地控制缓存行为。虽然直接动态地设置 cachenames 属性可能比较复杂,但我们可以通过直接操作 cachemanager 来实现动态缓存键。

核心思路:

不直接使用 @Cacheable 注解,而是通过 CacheManager 获取 Cache 对象,然后使用 cache.get(key, () -> …) 方法进行缓存。key 参数可以根据请求参数动态生成,而 () -> … 部分则定义了当缓存未命中时执行的操作。

实现步骤:

  1. 注入 CacheManager: 在 Controller 中注入 CacheManager。

    import org.springframework.cache.CacheManager; import org.springframework.cache.Cache; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; import org.springframework.http.HttpStatus;  @RestController public class TestController {      private final Cache myCache;      public TestController(@Autowired CacheManager cacheManager) {        this.myCache = cacheManager.getCache("myCache");     }
  2. 获取 Cache 对象: 使用 cacheManager.getCache(“cacheName”) 方法获取指定名称的 Cache 对象。 这里的 “myCache” 是缓存的名称,需要在 Spring Boot 的缓存配置中进行相应的配置。

  3. 使用 cache.get(key, () -> …) 方法: 在需要缓存的方法中,使用 cache.get(key, () -> …) 方法。key 参数是动态生成的缓存键,() -> … 部分是当缓存未命中时执行的 Lambda 表达式。

    动态缓存键在 Spring Boot 中的应用

    Groq

    GroqChat是一个全新的AI聊天机器人平台,支持多种大模型语言,可以免费在线使用。

    动态缓存键在 Spring Boot 中的应用77

    查看详情 动态缓存键在 Spring Boot 中的应用

    @GetMapping("/test/{name}") public String test(@PathVariable String name) {     return myCache.get(name, () -> {       // your expensive operation that needs to be cached.       System.out.println("########Test Called ###### " + name);       return HttpStatus.OK.toString();     }); }

    在上面的例子中,name 参数作为缓存键,如果缓存中不存在对应的 name,则会执行 lambda 表达式中的代码,并将结果缓存起来。下次使用相同的 name 参数访问该方法时,将直接从缓存中获取结果,而不会执行 lambda 表达式中的代码。

完整示例代码:

import org.springframework.cache.CacheManager; import org.springframework.cache.Cache; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; import org.springframework.http.HttpStatus;  @RestController public class TestController {      private final Cache myCache;      public TestController(@Autowired CacheManager cacheManager) {        this.myCache = cacheManager.getCache("myCache");     }      @GetMapping("/test/{name}")     public String test(@PathVariable String name) {         return myCache.get(name, () -> {           // your expensive operation that needs to be cached.           System.out.println("########Test Called ###### " + name);           return HttpStatus.OK.toString();         });     } }

注意事项:

  • 确保在 Spring Boot 的配置中启用了缓存,并配置了相应的 CacheManager。例如,可以使用 ConcurrentMapCacheManager 或 redis 等作为缓存管理器。
  • 缓存键的生成策略需要根据实际业务需求进行设计,确保缓存键的唯一性和有效性。
  • 需要根据实际情况设置缓存的过期时间,以避免缓存数据过期或占用过多内存。

总结:

虽然无法直接动态地设置 @Cacheable 注解的 cacheNames 属性,但通过直接操作 CacheManager,我们可以灵活地实现动态缓存键,从而更好地控制缓存行为。 这种方法虽然缓存名称是静态的,但缓存键的动态性已经可以满足大多数需要动态缓存的场景。 在实际应用中,需要根据具体需求选择合适的缓存策略和缓存管理器,以达到最佳的性能和效果。



评论(已关闭)

评论已关闭