
在 Spring Boot 应用中,使用 @Cacheable 注解可以方便地实现缓存功能。然而,在某些场景下,我们需要根据请求参数动态地生成缓存键,而不是简单地使用固定的键值。虽然 @Cacheable 注解允许通过 key 属性指定 SpEL 表达式来生成缓存键,但有时我们可能需要更灵活的控制,例如在缓存不存在时才进行计算并缓存结果。本文将介绍一种通过直接操作 CacheManager 来实现动态缓存键的方法。
使用 CacheManager 实现动态缓存键
不同于使用 @Cacheable 注解,我们可以直接通过 CacheManager 获取 Cache 对象,然后使用 cache.get(key, () -> ...) 方法来实现缓存的读取和更新。这种方法允许我们更灵活地控制缓存的逻辑。
以下是一个示例代码:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.Cache;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TestController {
private final Cache myCache;
@Autowired
public TestController(CacheManager cacheManager) {
this.myCache = cacheManager.getCache("myCache");
}
@GetMapping("/test/{name}")
public String test(@PathVariable String name) {
return myCache.get(name, () -> {
// 模拟耗时操作,需要被缓存
System.out.println("########Test Called ###### " + name);
return HttpStatus.OK.toString();
});
}
}代码解释:
注意事项:
总结:
通过直接操作 CacheManager,我们可以灵活地实现基于请求参数动态生成缓存键的策略。这种方法避免了直接动态修改 cacheNames 的复杂性,提供了更简洁、可维护的解决方案。在需要更精细化的缓存管理时,这种方法是一种不错的选择。虽然缓存名称本身并没有动态化,但缓存键的动态性足以满足大多数场景的需求。
以上就是动态缓存键配置:Spring Boot 缓存管理的灵活应用的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号