Spring Cache 中如何优雅地添加常量到 Key?

Spring Cache Key 中优雅地集成常量

在使用 Spring Cache 时,如何在 Key 中有效地添加常量值?本文提供两种简洁的解决方案:

方案一:利用 Bean 属性

将常量值定义为 Bean 的属性,并在 @Cacheable 注解的 key 属性中引用该 Bean 属性。

方案二:运用 Spring EL 表达式

使用 Spring 表达式语言 (EL) 在 key 属性中直接拼接常量。EL 表达式用花括号 {} 包裹,并以 # 符号开头,后面跟着 Bean 属性名或直接值。

代码示例:

方案一:

首先,定义一个 Bean 来保存常量值:

@Service
public class CurrentContext {

    private static final ThreadLocal currentId = new ThreadLocal<>();

    public void setCurrentId(String id) {
        currentId.set(id);
    }

    public String getCurrentId() {
        return currentId.get();
    }
}

然后在需要缓存的方法上使用 @Cacheable 注解:

@Service
public class MyService {

    @Autowired
    private CurrentContext currentContext;

    @Cacheable(value = "shoppingcar", key = "#currentContext.getCurrentId() + '_car'")
    public Object getShoppingCartData() {
        // ... 获取购物车数据 ...
    }
}

方案二:

接在 @Cacheable 注解的 key 属性中使用 Spring EL 表达式:

@Service
public class MyService {

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

这两种方法都能有效地将常量添加到 Cache Key 中,选择哪种方法取决于具体场景和个人偏好。 方案一更适合需要复用常量的场景,而方案二则更简洁直接。 需要注意的是,ThreadLocal 的使用需要谨慎,确保在使用完毕后进行清理,避免内存泄漏。