zl程序教程

您现在的位置是:首页 >  后端

当前栏目

spring cache注意事项

Spring 注意事项 cache
2023-06-13 09:15:25 时间

文章目录[隐藏]

@Cacheable注解类内部调用失效问题

在使用Spring @Cacheable注解的时候,要注意,如果类A的方法f()被标注了@Cacheable注解,那么当类A的其他方法,例如:f2(),去直接调用f()的时候,@Cacheable是不起作用的,原因是@Cacheable是基于Spring AOP代理类,f2()属于内部方法,直接调用f()时,是不走代理的。举个例子:

@Cacheable(key = "#entityType", value = "entityCache")
public List<String> selectByEntityType(int entityType) {
    List<String> result = new ArrayList<>();
    // do something
    return result;
}
public List<String> f2(){
    // Cacheable失效,不会走缓存的
    selectByEntityType(1);
}

解决方法就是不让这两个方法在同一个类中

@CacheEvict 清除多个key

借用@Caching实现

#入参是基本类型的:
@Caching(evict={@CacheEvict(value = Cache.CONSTANT, key = "'" + CacheKey.SINGLE_ROLE_NAME + "'+#roleId"),
            @CacheEvict(value = Cache.CONSTANT, key = "'" + CacheKey.ROLES_NAME + "'+#roleId"),
            @CacheEvict(value = Cache.CONSTANT, key = "'" + CacheKey.SINGLE_ROLE_NAME + "'+#roleId")})
public ResponseData remove(@RequestParam Long roleId) {
………………
}

#入参是对象的:
@Caching(evict={@CacheEvict(value = Cache.CONSTANT, key = "'" + CacheKey.SINGLE_ROLE_NAME + "'+#roleDto.roleId"),
            @CacheEvict(value = Cache.CONSTANT, key = "'" + CacheKey.ROLES_NAME + "'+#roleDto.roleId"),
            @CacheEvict(value = Cache.CONSTANT, key = "'" + CacheKey.SINGLE_ROLE_NAME + "'+#roleDto.roleId")})
    public ResponseData edit(RoleDto roleDto) {
        this.roleService.editRole(roleDto);
        return SUCCESS_TIP;
}