Consider the following method:

  @Cacheable(value = "foo", key = "#season.toString()", cacheManager = "foo_cache")
  public List<League> getLeaguesBySeason(
          String season) {
    //makes call to actual datasource to get the data
    List<League> result = this.fetchLeagues(List.of(), season);
    return result;
  }

Now assume that for some reason the cache is not reachable. Example, the redis server is down or some on going network issue prevents us from reaching the reaching the redis server. I have configured a custom CacheErrorHandler that just logs the exception in the handleCacheGetError method of the CustomCacheErrorHandler. This will in effect treat the exception as a cache miss and then proceed inside the getLeaguesBySeason method to fetch the data from the actual data source. This is good so far. However, after the data is fetched the behavior in Spring is that the @Cacheable annotation will automatically attempt to update the data in cache by doing a put operation. Now this is good default behavior; however, in our case we want to avoid doing the put operation if we know that the redis is unreachable.

There are performance concerns here on the application sidel and therefore we would like to customize the behavior of @Cachebale as follows.

If the preceding get operation failed due to a timeout or a connection exception, then we would like to retrieve the data from the actual datasource and then avoid the process of updating the cache as a final step.

Is this possible?

Comment From: jhoeller

On review, this turns out to be hard to provide as described due to the complexity of multi-cache interactions in CacheAspectSupport. However, this is close to the natural behavior of @Cacheable(sync=true) where the get/put operation is performed in a "synchronized" fashion against the target cache, so I would simply recommend to switch to that style of interaction. And if the target cache implementation nevertheless tries to perform another I/O operation for a final put step when the get step already failed for a single value-loader operation, an enhancement request should be raised against that cache provider.