0

I'm using Spring Boot 2.3 and I'm using the default cache mechanism using app.properties. I defined all values:

spring.cache.type = redis
spring.redis.host = host
spring.redis.port = port
spring.redis.timeout = 4000
spring.redis.password = psw
spring.cache.redis.time-to-live = 28800000

I take advantage of the cache in Spring Repository for example:

    @Cacheable(cacheNames = "contacts")
    @Override
    Page<Contact> findAll(Specification specification, Pageable pageable);

It works as expected. Redis, however is a cluster used from a couple of my applications and I need the second application is able to remove some/all keys in redis.

The applicazione A1 take advantage of the cache and put keys inside. The app A2, need to clear some keys or all keys.

In A2 I did:

cacheManager.getCacheNames().forEach(cacheName -> cacheManager.getCache(cacheName).clear());

but of course the list of cache names is empty becuase in this app I don't add keys to the cache and, anyway, I don't have the same keys of the A1. I should list remote keys and then I need to clear them. Is there a simple way without using Spring Data Redis library?

drenda
  • 5,846
  • 11
  • 68
  • 141

1 Answers1

0

You could define a separate prefix for entire your cache in the Redis. Something like a namespace for your cache entries. And after you could flush all keys in this namespace.

Note: ensure that CacheManager has only Redis cache and doesn't have an in-memory cache (L1).

Andrei Kovrov
  • 2,087
  • 1
  • 18
  • 28
  • Thanks, can you provide an example to clear the cache by prefix? – drenda Oct 08 '20 at 12:02
  • If you ask about a general approach you can find a good discussion about it [here](https://stackoverflow.com/questions/4006324/how-to-atomically-delete-keys-matching-a-pattern-using-redis) – Andrei Kovrov Oct 08 '20 at 13:29
  • Asking doing that from Spring. Thanks – drenda Oct 08 '20 at 14:25
  • 1
    The approach for Spring should be the same: retrieve keys for prefix via `RedisTemplate#keys` and use `RedisTemplate#delete` to delete them – Andrei Kovrov Oct 08 '20 at 14:41