Search code examples
spring-bootcachinggoogle-cloud-platformredisgoogle-cloud-memorystore

Modify @Cacheable spring annotation to use a secondary cacheManager for writing values to cache


I am connecting to Google Cloud Platform memorystore Redis with Read replica enabled. It exposes 2 endpoints:

  1. Primary for writing to Redis Cache
  2. 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:

    1. Add unless attribute inside @Cacheable as follows:

    @Cacheable(unless="isReadReplicaEnabled") public Data getData()

    1. 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()

    1. Inside the method annotated with @Cacheable call the writeToCache method if the read replica is enabled:

    if(isReadReplicaEnabled()){ writeToCache(); }