在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,我们可以实现基于请求参数的动态缓存键配置,从而更灵活地控制缓存行为。虽然缓存名称是静态的,但动态的缓存键已经能够满足大部分场景的需求。在实际应用中,需要根据具体情况选择合适的缓存策略和配置,并注意并发和序列化等问题,以保证缓存的正确性和性能。