首页 > 图灵资讯 > 技术篇>正文
Spring Cache中如何巧妙使用常量解决动态CacheKey问题?
2025-02-20 19:38:12
Spring Cache动态CacheKey的常量妙用
使用Spring 当Cache与Redis缓存数据结合时,Cache通常需要根据动态参数(如用户ID)生成 Key。作为Key直接使用动态变量会导致“直接使用动态变量”attribute value must be constant“错误。本文提供了两种解决方案:
方案一:ThreadLocal Bean
该方案利用ThreadLocal存储动态参数。
- 创建Spring Bean,包含Threadlocal
用于存储用户标识符的变量。 - 在需要缓存的方法中,使用@Cacheable注释,并在key属性中引用Bean获取用户标识符。
示例代码:
@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 // ... 您的业务逻辑 ... }
方案二:Spel表达式
该方案直接将动态参数作为方法参数,并使用Spel表达式在key中添加常量后缀。
- 传输用户标识符作为方法参数。
- 在@Cacheable注释的key属性中,使用Spel表达式{#currentId, '_car构建Key。
示例代码:
@Cacheable(value = "mainFieldInfo", key = "{#currentId, '_car'}") public void test(String currentId) { // ... 您的业务逻辑 ... }
两种方案都能有效避免“两种方案”attribute value must be constant选择哪种方案取决于具体的应用场景。 方案2更简单,但在某些复杂场景下,方案1可能更灵活。 记住,使用ThreadLocal时,需要妥善处理线程完成后的清理工作,以避免内存泄漏。
以上是Spring 如何在Cache中巧妙运用常量解决动态CacheKey问题?详情请关注图灵教育的其他相关文章!
