spring cache注解@Cacheable参数key赋值

1 参数

@Cacheable(key ="#id")

一般这里会是 id ,但是可能与其它 entity的id重复。

2 前缀加参数

@Cacheable(key = "'com:test:'+#id")

但是给 key 赋值 会导致代码不够优雅,因为 缓存、更新、失效 都要给key赋值。
可以定义全局变量解决此问题
public static final String KEY_NAME = "'com:test:'";
@Cacheable(key = KEY_NAME +"+#id")

public class Constant {
    public static final String yky_auth_user_role_CacheName = "yky-auth:cache:userRole:";
    public static final String yky_auth_permission_CacheName = "yky-auth:cache:permission:";
    
    public static final String prefix_yky_auth_user_role_CacheName = "'yky-auth:cache:userRole:'";
    public static final String prefix_yky_auth_permission_CacheName = "'yky-auth:cache:permission:'";

}
 

@Cacheable(value=Constant.yky_auth_user_role_CacheName,key=Constant.prefix_yky_auth_user_role_CacheName+"+#root.targetClass.name +\":\"+ #root.methodName+#userId")
    @Override
    public List<SysRole> getRoleByUserId(String userId) {
        
         return userRepository.getRoleByUserId(userId);
    }

3 自定义keyGenerator

@Cacheable(keyGenerator="keyGenerator")

@Override
    public KeyGenerator keyGenerator() {
        return new KeyGenerator() {
            @Override
            public Object generate(Object target, Method method, Object... params) {
                StringBuilder sb = new StringBuilder();
                sb.append(target.getClass().getName()).append(":");
                sb.append(method.getName()).append(":");
                for (Object obj : params) {
                    sb.append(obj.toString());
                }
                return sb.toString();
            }
        };
    }

4 指定类名和方法名

@Cacheable(key ="#root.targetClass.name +\":\"+ #root.methodName")

一般这里会是 id ,但是可能与其它 entity的id重复。

@Cacheable(value=Constant.yky_auth_permission_CacheName,key=Constant.prefix_yky_auth_permission_CacheName+"+#root.targetClass.name +\":\"+ #root.methodName")
    @Override
    public List<PermissionAndRole> getAll() {
        
        
        return permissionAndRoleRepository.getAll();
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值