spring-projects / spring-framework

Spring Framework
https://spring.io/projects/spring-framework
Apache License 2.0
56.77k stars 38.16k forks source link

`@Cacheable` behavior when there is a `QueryTimeoutException` on the get operation #33790

Open chiku80 opened 1 month ago

chiku80 commented 1 month ago

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?