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();
    }

 

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐