Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring @Cachable updating data

example from : SpringSource

@Cacheable(value = "vets")
public Collection<Vet> findVets() throws DataAccessException {
    return vetRepository.findAll();
}

How does findVets() work exactly ?

For the first time, it takes the data from vetRepository and saves the result in cache. But what happens if a new vet is inserted in the database - does the cache update (out of the box behavior) ? If not, can we configure it to update ?


EDIT:

But what happens if the DB is updated from an external source (e.g. an application which uses the same DB) ?

like image 235
Horatiu Jeflea Avatar asked Apr 26 '13 11:04

Horatiu Jeflea


People also ask

How does @cachable work?

As the name implies, @Cacheable is used to demarcate methods that are cacheable - that is, methods for whom the result is stored into the cache so on subsequent invocations (with the same arguments), the value in the cache is returned without having to actually execute the method.

How does Spring cache work internally?

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.


1 Answers

@CachePut("vets")    
public void save(Vet vet) {..}

You have to tell the cache that an object is stale. If data change without using your service methods then, of course, you would have a problem. You can, however, clear the whole cache with

@CacheEvict(value = "vets", allEntries = true)    
public void clearCache() {..}

It depends on the Caching Provider though. If another app updates the database without notifying your app, but it uses the same cache it, then the other app would probably update the cache too.

like image 74
a better oliver Avatar answered Oct 12 '22 23:10

a better oliver