spring-data-redisspring-cacheredis-cache

Evict cache for multiple keys rather than all in Spring Redis


Is there any way we can evict cache for only a selected number of keys rather than evicting all entries:

@CacheEvict(value = BOOKS_CACHE, allEntries = true)
public int deleteByIds(final Collection<Long> booksIds) {
    // Delete all DB entries for given bookIds
}

I don't want to evict all entries but only who are in Collections. Please suggest. Thanks


Solution

  • A similar question was asked in the past.

    Essentially, if your keys follow a pattern, then with Redis in particular, you can use REGEX to match on keys for entries you wanted evicted from the Redis cache.

    I never responded to this question specifically since the answer was adequate, and asked in the context of Redis. However, it did inspire me to generalize the solution a bit further in order to apply this technique beyond Redis.

    If you are curious, you can have a look at the more generalized solution in this test class, which applies the given Redis solution along with a solution for Apache Geode and 1 last solution when a simple ConcurrentMap is used as the backing cache in Spring's Cache Abstraction.

    Of course, the more generalized solution requires some extension(s) (beginning here) to the core Spring Framework Cache Abstraction.

    Anyway, hopefully this will give you some ideas how to cater these solutions to your use case. I am sure there are other possibilities as well.

    Obviously, mileage will vary based on the caching provider (e.g. Redis) used with Spring's Cache Abstraction along with the requirements for your application use case.