Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring caching - do not cache in case of error

I am using spring caching, my question is:

How can I control the caching in case the result is an error and the next request could be good?

example:

@Cacheable("mycache")
public  ResponceBO getBigObject(String id) throws Exception {

    boolean isError = false;

    ***   load big object from other service,  can be loaded with errors  ***
    isError = true;

    if(error){
       responceBO.setError(true);
    }

    return responceBO;
}

In case of an error I don't want to cache the object, what can I do instead?

like image 506
prilia Avatar asked Jul 23 '15 07:07

prilia


People also ask

How does Spring caching work?

Spring Cache uses the parameters of the method as key and the return value as a value in the cache. When the method is called the first time, Spring will check if the value with the given key is in the cache. It will not be the case, and the method itself will be executed.

Does spring data cache?

Spring Data JDBC concentrates on its job: persisting and loading aggregates. Caching is orthogonal to that and can be added using the well known Spring Cache abstraction. The complete example code is available in the Spring Data Example repository.


1 Answers

I would suggest reading the conditional caching section of the reference guide. Basically simply specify a unless expression to prevent the caching. (The result placeholder is only available for the unless statement not the condition statement.

@Cacheable("mycache", unless="#result.error")
public  ResponceBO getBigObject(String id) throws Exception { ... }

Should do the trick.

like image 151
M. Deinum Avatar answered Sep 21 '22 20:09

M. Deinum