首页 > Java > java教程 > 正文

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

聖光之護
发布: 2025-09-09 19:43:01
原创
431人浏览过

动态缓存键在 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 表达式。

    AppMall应用商店
    AppMall应用商店

    AI应用商店,提供即时交付、按需付费的人工智能应用服务

    AppMall应用商店 56
    查看详情 AppMall应用商店
    @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,我们可以灵活地实现动态缓存键,从而更好地控制缓存行为。 这种方法虽然缓存名称是静态的,但缓存键的动态性已经可以满足大多数需要动态缓存的场景。 在实际应用中,需要根据具体需求选择合适的缓存策略和缓存管理器,以达到最佳的性能和效果。

以上就是动态缓存键在 Spring Boot 中的应用的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号