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

如何在不使用Scheduled注解的情况下清除Spring Cache

Spring Cache 非定时任务方式清除缓存

以下是几种无需定时任务即可清除Spring Cache的实用方案:

1. 注解式主动清除

通过@CacheEvict注解直接绑定方法,方法执行时自动触发缓存清除操作:

  • 清除单个指定key的缓存:
    @CacheEvict(value = "userCache", key = "#userId")
    public void updateUser(Long userId, User user) {
        // 数据库更新逻辑
    }
    
  • 清除整个缓存命名空间的所有缓存项:
    @CacheEvict(value = "userCache", allEntries = true)
    public void clearAllUserCache() {
        // 无需额外业务逻辑,注解自动执行清除
    }
    
  • 组合多个缓存清除操作可使用@Caching:
    @Caching(evict = {
        @CacheEvict(value = "userCache", key = "#user.id"),
        @CacheEvict(value = "roleCache", key = "#user.roleId")
    })
    public void updateUserInfo(User user) {
        // 业务处理逻辑
    }
    

2. 手动调用CacheManager操作缓存

注入CacheManager直接获取缓存实例,在业务逻辑中灵活控制缓存清除:

@Autowired
private CacheManager cacheManager;

public void clearTargetCache(String cacheName, String cacheKey) {
    Cache targetCache = cacheManager.getCache(cacheName);
    if (targetCache != null) {
        targetCache.evict(cacheKey); // 清除单个key
        // targetCache.clear(); // 清除该缓存下所有条目
    }
}

3. 事件驱动型缓存清除

基于Spring事件机制,在业务事件触发时(如数据更新),通过监听事件完成缓存清除:

  • 定义自定义事件类:
    public class UserUpdatedEvent extends ApplicationEvent {
        private final Long userId;
    
        public UserUpdatedEvent(Object source, Long userId) {
            super(source);
            this.userId = userId;
        }
    
        public Long getUserId() {
            return userId;
        }
    }
    
  • 在业务方法中发布事件:
    @Autowired
    private ApplicationEventPublisher eventPublisher;
    
    public void updateUser(Long userId, User user) {
        // 执行数据库更新
        eventPublisher.publishEvent(new UserUpdatedEvent(this, userId));
    }
    
  • 编写事件监听器处理缓存清除:
    @Component
    public class CacheCleanupListener {
        @Autowired
        private CacheManager cacheManager;
    
        @EventListener
        public void handleUserUpdateEvent(UserUpdatedEvent event) {
            Cache userCache = cacheManager.getCache("userCache");
            if (userCache != null) {
                userCache.evict(event.getUserId());
            }
        }
    }
    

4. 配置缓存过期策略(被动清除)

如果对缓存时效性要求不高,可通过配置缓存过期时间让缓存自动失效,以Redis缓存为例:

@Configuration
@EnableCaching
public class RedisCacheConfig {
    @Bean
    public RedisCacheManager cacheManager(RedisConnectionFactory connectionFactory) {
        RedisCacheConfiguration defaultConfig = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofMinutes(30)) // 设置默认缓存有效期30分钟
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));

        return RedisCacheManager.builder(connectionFactory)
                .cacheDefaults(defaultConfig)
                .build();
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 05:27:08