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