Spring Cache中如何巧妙使用常量解决动态CacheKey问题?

Spring Cache动态CacheKey的常量妙用

在使用Spring Cache结合Redis缓存数据时,经常需要根据动态参数(例如用户ID)生成Cache Key。直接使用动态变量作为Key会导致“attribute value must be constant”错误。本文提供两种解决方案:

方案一:ThreadLocal Bean

此方案利用ThreadLocal存储动态参数。

  1. 创建一个Spring Bean,包含一个ThreadLocal变量用于存储用户标识符。
  2. 在需要缓存的方法中,使用@Cacheable注解,并在key属性中引用该Bean的方法获取用户标识符。

示例代码:

@Service
public class CurrentUser {
    private static final ThreadLocal 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 cur

rentUser, String currentId) { currentUser.setCurrentId(currentId); // 设置用户ID // ... 你的业务逻辑 ... }

方案二:SpEL表达式

此方案直接将动态参数作为方法参数,并使用SpEL表达式在key中添加常量后缀。

  1. 将用户标识符作为方法参数传入。
  2. @Cacheable注解的key属性中,使用SpEL表达式{#currentId, '_car'}构建Key。

示例代码:

@Cacheable(value = "mainFieldInfo", key = "{#currentId, '_car'}")
public void test(String currentId) {
    // ... 你的业务逻辑 ...
}

两种方案都能有效避免“attribute value must be constant”错误,选择哪种方案取决于具体应用场景。 方案二更简洁,但方案一在某些复杂场景下可能更灵活。 记住在使用ThreadLocal时,需要妥善处理线程结束后的清理工作,避免内存泄漏。