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

Spring Boot中使用@CacheEvict批量删除Redis缓存失效问题

问题原因分析

批量删除后缓存未同步清除的核心问题在于**@CacheEvict注解的key绑定逻辑错误**:

  • 单个Post缓存的key是Long类型的单条postId,但控制器上的@CacheEvict(value="Post", key="#postId")中,#postId是List<Long>类型。
  • Spring Cache会将整个列表作为key去匹配缓存条目,但实际不存在以该列表为key的缓存,因此批量删除时无法清除任何单条Post的缓存。
解决方案

推荐将缓存清除逻辑移到服务层的单条删除方法中,通过循环调用单删方法实现批量删除+缓存同步:

1. 修改服务层代码

新增带缓存清除注解的单条删除方法,批量删除时循环调用该方法:

// 单条删除方法,添加@CacheEvict清除对应缓存
@CacheEvict(value = "Post", key = "#postId")
public void deletePost(Long postId, String emailAddress) {
    Post post = findPostById(postId, emailAddress);
    postRepository.delete(post);
}

// 批量删除方法改为循环调用单删
public void deleteMultiplePosts(List<Long> postIdList, String emailAddress) {
    for (Long postId : postIdList) {
        deletePost(postId, emailAddress);
    }
}

2. 移除控制器上无效的@CacheEvict注解

控制器层无需保留该注解,修改后代码:

@DeleteMapping("/posts/{postId}")
public ResponseEntity<?> deletePosts(@PathVariable List<Long> postId, Principal principal) {
    postService.deleteMultiplePosts(postId, principal.getName());
    return new ResponseEntity<>(createMapForPageContents(postService.findAllActivePostsByPostCreator(principal.getName(), PageRequest.of(0, 5))), HttpStatus.OK);
}

备选方案:手动调用RedisTemplate清除缓存

若不想拆分方法,可在批量删除后手动遍历postId列表,调用RedisTemplate逐个清除缓存:

@Autowired
private RedisTemplate<String, Object> redisTemplate;

public void deleteMultiplePosts(List<Long> postIdList, String emailAddress) {
    List<Post> posts = new ArrayList<>();
    for (Long postId : postIdList) {
        posts.add(findPostById(postId, emailAddress));
    }
    postRepository.deleteAll(posts);
    
    // 手动清除每个postId对应的缓存(Spring Cache默认key格式为「缓存名::key」)
    for (Long postId : postIdList) {
        redisTemplate.delete("Post::" + postId);
    }
}

注意:使用手动清除方式时,需确保Spring Cache的key生成规则与拼接格式一致,若自定义过key生成策略,需对应调整拼接逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 11:45:37