Issue
I am connecting to Google Cloud Platform memorystore Redis with Read replica enabled. It exposes 2 endpoints:
- Primary for writing to Redis Cache
- Read Replica for reading from Redis Cache
I have created 2 Cache managers to connect to these endpoints. Now using @Cacheable
annotation I can only specify one cache manager at a time. I need to specify a specific Cache manager for reading from cache and another one to write to the cache. I figured, I need to extend the behavior of @Cacheable
to add a secondary Cache manager which can be used to write to the primary endpoint.
Is it possible to do so in Spring and if so, what is the process to achieve this behavior. Any pointers will be greatly appreciated.
Solution
This is how I was able to modify the @Cacheable behavior:
- Add
unless
attribute inside @Cacheable as follows:
@Cacheable(unless="isReadReplicaEnabled") public Data getData()
- Create a new method annotated with
@CachePut
in new class to use new cache manager which connects to Primary redis instance,as below:
@CachePut(cacheManager ="primaryCacheManager") public void writeToCache()
- Inside the method annotated with @Cacheable call the
writeToCache
method if the read replica is enabled:
if(isReadReplicaEnabled()){ writeToCache(); }
Answered By - Ravi Mishra
Answer Checked By - Cary Denson (JavaFixing Admin)