Commit b5e98be1 authored by Jamie Tanna's avatar Jamie Tanna

Blogument Spring `CacheEvict`

parent dec742a7
Pipeline #150848529 passed with stages
in 11 minutes and 43 seconds
title: "Evicting Spring Cache on a Schedule"
description: "How to evict Spring Cache's `@Cacheable` data on a schedule."
- blogumentation
- java
- spring
- spring-cache
license_code: Apache-2.0
license_prose: CC-BY-NC-SA-4.0
date: 2020-05-29T10:20:00+0100
slug: "evict-spring-cache-schedule"
If you're using [Spring Cache](, you may want to evict the cache on a schedule, to keep it updated.
If you're using out-of-the-box caching with Spring 5 (tested with v5.1.6) you can do something similar to the following:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
@EnableScheduling // remember this so your `@Scheduled` get picked up
public class CacheConfiguration {
public static final String EVENTS_CACHE = "events";
public static final String GROUPS_CACHE = "groups";
private static final Logger LOGGER = LoggerFactory.getLogger(CacheConfiguration.class);
private static final long SIX_HOURS = Timer.ONE_HOUR * 6;
@Scheduled(fixedRate = Timer.ONE_HOUR)
value = {EVENTS_CACHE},
allEntries = true)
public void clearEvents() {"Clearing events caches");
@Scheduled(fixedRate = SIX_HOURS)
value = {GROUPS_CACHE},
allEntries = true)
public void clearGroups() {"Clearing groups caches");
**Note** the `allEntries = true` is essential, [as noted by Johannes Di on _Schedule Spring cache eviction?_]( otherwise `@CacheEvict` will be a no-op.
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment