
在 spring boot 应用中,使用 @cacheable 注解可以方便地实现缓存功能。然而,有时我们需要根据请求参数动态地生成缓存键,以更精细地控制缓存行为。虽然直接动态地设置 cachenames 属性可能比较复杂,但我们可以通过直接操作 cachemanager 来实现动态缓存键。
核心思路:
不直接使用 @Cacheable 注解,而是通过 CacheManager 获取 Cache 对象,然后使用 cache.get(key, () -> ...) 方法进行缓存。key 参数可以根据请求参数动态生成,而 () -> ... 部分则定义了当缓存未命中时执行的操作。
实现步骤:
注入 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");
}获取 Cache 对象: 使用 cacheManager.getCache("cacheName") 方法获取指定名称的 Cache 对象。 这里的 "myCache" 是缓存的名称,需要在 Spring Boot 的缓存配置中进行相应的配置。
使用 cache.get(key, () -> ...) 方法: 在需要缓存的方法中,使用 cache.get(key, () -> ...) 方法。key 参数是动态生成的缓存键,() -> ... 部分是当缓存未命中时执行的 lambda 表达式。
@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();
});
}
}注意事项:
总结:
虽然无法直接动态地设置 @Cacheable 注解的 cacheNames 属性,但通过直接操作 CacheManager,我们可以灵活地实现动态缓存键,从而更好地控制缓存行为。 这种方法虽然缓存名称是静态的,但缓存键的动态性已经可以满足大多数需要动态缓存的场景。 在实际应用中,需要根据具体需求选择合适的缓存策略和缓存管理器,以达到最佳的性能和效果。
以上就是动态缓存键在 Spring Boot 中的应用的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号