Home > Blockchain >  Is it possible to @CacheEvict keys that match a pattern?
Is it possible to @CacheEvict keys that match a pattern?

Time:11-06

Is there something along the lines of @CacheEvict(value = "FOO", key = "baz*") so that when the cache FOO contains keys baz_1 and baz_2 they get evicted?

CodePudding user response:

Assuming that you have spring-boot-starter-cache as dependency, spring boot auto-configures a CacheManager bean named cacheManager.

Also, assuming you have spring-boot-starter-data-redis as a dependency, RedisCacheManager is picked as the CacheManager implementation.

@CacheEvict (and the caching abstraction API) doesn't let you the option to evict by prefix, but using an AOP advice (or elsewhere where fits), you can take advantage of the underlying implementation:

    RedisCache redisCache = (RedisCache) cacheManager.getCache("FOO");
    redisCache.getNativeCache().clean("FOO",  "baz*".getBytes());

Didn't try it actually, but I think this should work.

Likewise, you can adapt to other caching implementation.

The shortcoming of this approach, is that you'll have to change your code upon changing the cache implementation.

  • Related