You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Redis缓存中@CacheEvict无法清除缓存条目问题排查

问题分析与解决:Spring Redis缓存@CacheEvict无效

问题描述

在Spring中使用Redis实现缓存服务时,save方法的@CachePut注解工作正常,但delete方法的@CacheEvict注解无法清除对应缓存条目。尝试过硬编码key、通过CacheManager清除全部缓存(此操作有效),但按key清除缓存始终无效,即使使用与save方法相同的key也不行。

缓存服务代码

@Service
public class PermissionCachingService {

    @Autowired
    PermissionRepository permissionRepository;


    @CachePut(value = "Permission", key = "#permission.id")
    public Permission save(Permission permission) {
        return permissionRepository.save(permission);
    }

    @CacheEvict(value = "Permission", key = "#permission.id")
    void delete(Permission permission) {
        permissionRepository.delete(permission);
    }

}

Permission实体类代码

@Entity
public class Permission {

    @Id
    @NotNull
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    Long id;

    @NotNull
    Boolean read = false;

    @NotNull
    Boolean write = false;

    @NotNull
    Boolean update = false;

    @NotNull
    @ManyToOne
    Resource resource;


    Long  groupId;

    // 构造方法
    // setter和getter方法
}

核心问题

delete方法是包私有(default)访问权限,而Spring的缓存注解(如@CacheEvict)依赖Spring AOP实现拦截,Spring AOP默认只能代理public修饰的方法。非public方法无法被Spring的代理机制拦截,导致@CacheEvict注解完全不生效。

解决方案

将delete方法的访问权限修改为public:

@Service
public class PermissionCachingService {

    @Autowired
    PermissionRepository permissionRepository;


    @CachePut(value = "Permission", key = "#permission.id")
    public Permission save(Permission permission) {
        return permissionRepository.save(permission);
    }

    @CacheEvict(value = "Permission", key = "#permission.id")
    public void delete(Permission permission) {
        permissionRepository.delete(permission);
    }

}

额外检查点

  • 确保调用delete方法时,传入的Permission对象的id属性不为null,且与缓存中存储的key一致
  • 确认Spring缓存配置正确,Redis缓存管理器已正确初始化并关联到"Permission"缓存名称

内容的提问来源于stack exchange,提问作者Karim Halayqa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 20:05:25