
在Spring Boot应用中,我们常常需要根据不同的请求参数来缓存数据,以避免重复计算和提高响应速度。@Cacheable注解提供了一种便捷的缓存机制,但其cacheNames属性是静态的,无法直接根据请求参数动态设置。本文将介绍一种更灵活的方法,通过直接操作CacheManager来实现基于请求参数的动态缓存键配置。
使用CacheManager实现动态缓存键
以下代码展示了如何通过CacheManager获取缓存对象,并使用请求参数作为缓存键:
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,我们可以实现基于请求参数的动态缓存键配置,从而更灵活地控制缓存行为。虽然缓存名称是静态的,但动态的缓存键已经能够满足大部分场景的需求。在实际应用中,需要根据具体情况选择合适的缓存策略和配置,并注意并发和序列化等问题,以保证缓存的正确性和性能。
以上就是动态缓存键配置:Spring Boot缓存的灵活应用的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号