In a Spring Boot app I'm doing the migration from a local cache implemented with Caffeine
to a Redis
distributed cache.
I see in Caffeine
cache that we can set the maximum number of entries
Cache cache = new CaffeineCache(cacheName, Caffeine.newBuilder()
.recordStats()
.expireAfterWrite(expireIn, TimeUnit.SECONDS)
.maximumSize(maxSize)
.build());
Can the same be achieved in code for Redis
? I need to set the different values for different cache names.
No, it's not possible there're two reasons for that.
Spring does not support setting maxSize for Redis cache Refer: RedisCacheConfiguration
Even if Spring would be supporting this then it would be difficult to track active cache entries.
To support max size, we would need detail about currently non-expired/non-evicted keys. Finding these would require scanning all the cache keys. One simple way could be tracked all the cache key in another Redis SET data structure. As you have active cache keys now we need to apply some background policy to delete one or more keys. Deleting these keys is not easy as well, you need to see which one should be deleted, FIFO, LRU, or ?.
I would suggest implementing your own algorithm with the help of RedisCacheWriter
. Here while adding/removing to the cache, you can update your cache keys. Also, you need to run a background job that would run at certain intervals to cap the active cache entries.