1.在常量类中定义商品缓存空间和商品缓存KEY
public interface CacheConstants {/*** Goods Cache Name*/String QNA_GOODS_CACHE = "qna-goods";/*** Goods Cache key*/String QNA_GOODS_CACHE_KEY = "qna_goods:";/*** Order Cache Name*/String QNA_ORDER_CACHE = "qna-order";/*** Order Cache Key*/String QNA_ORDER_CACHE_KEY = "qna_order:";}
2.Cacheable中如何使用
1.引用静态常量
用 T(全类名).静态常量名 格式引用类的静态成员(T() 是 SpEL 中引用类的语法)。
例如:CacheConstants 类的包路径是 com.example.constants,则写成 T(com.example.constants.CacheConstants).QNA_GOODS_CACHE_KEY。
2.字符串拼接
常量与参数之间必须用 + 连接,确保 SpEL 正确解析为拼接后的字符串(如 qna_goods:123,其中 123 是 goodsId 的值)。
3.简化写法(若常量是固定前缀)
若 QNA_GOODS_CACHE_KEY 本身就是类似 qna_goods: 的固定前缀,也可以直接在表达式中写死前缀(不推荐,不利于维护):
key = "'qna_goods:' + #goodsId" // 直接写死前缀,避免引用类
3.使用方法
import org.springframework.cache.annotation.Cacheable;// 正确写法:引用静态常量 + 拼接参数
@Cacheable(value = CacheConstants.QNA_GOODS_CACHE,key = "T(com.yourpackage.CacheConstants).QNA_GOODS_CACHE_KEY + #goodsId"
)
public Goods getGoods(Long goodsId) {// 业务逻辑
}