
Spring Cache动态CacheKey的常量妙用
在使用Spring Cache结合Redis缓存数据时,经常需要根据动态参数(例如用户ID)生成Cache Key。直接使用动态变量作为Key会导致“attribute value must be constant”错误。本文提供两种解决方案:
方案一:ThreadLocal Bean
此方案利用ThreadLocal存储动态参数。
@Cacheable注解,并在key属性中引用该Bean的方法获取用户标识符。示例代码:
<code class="java">@Service
public class CurrentUser {
private static final ThreadLocal<String> threadLocal = new ThreadLocal<>();
public void setCurrentId(String currentId) {
threadLocal.set(currentId);
}
public String getCurrentId() {
return threadLocal.get();
}
}
@Cacheable(value = "shoppingcar", key = "#currentUser.getCurrentId() + '_car'")
public void test(@Autowired CurrentUser currentUser, String currentId) {
currentUser.setCurrentId(currentId); // 设置用户ID
// ... 你的业务逻辑 ...
}</code>方案二:SpEL表达式
此方案直接将动态参数作为方法参数,并使用SpEL表达式在key中添加常量后缀。
@Cacheable注解的key属性中,使用SpEL表达式{#currentId, '_car'}构建Key。示例代码:
<code class="java">@Cacheable(value = "mainFieldInfo", key = "{#currentId, '_car'}")
public void test(String currentId) {
// ... 你的业务逻辑 ...
}</code>两种方案都能有效避免“attribute value must be constant”错误,选择哪种方案取决于具体应用场景。 方案二更简洁,但方案一在某些复杂场景下可能更灵活。 记住在使用ThreadLocal时,需要妥善处理线程结束后的清理工作,避免内存泄漏。
以上就是Spring Cache中如何巧妙使用常量解决动态CacheKey问题?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号