问题
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) ?
回答1:
@CacheEvict("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.
回答2:
It would not do it automatically and there is not way for the cache to know if the data has been externally introduced.
Check @CacheEvict
which will help you invalidate the cache entry in case of any change to the underlying collections.
@CacheEvict(value = "vet", allEntries = true)
public void saveVet() {
// Intentionally blank
}
allEntries
Whether or not all the entries inside the cache(s) are removed or not.
By default, only the value under the associated key is removed. Note that specifying setting this parameter to true and specifying a key is not allowed.
回答3:
you also can use @CachePut on the method which creates the new entry. The return type has to be the same as in your @Cachable method.
@CachePut(value = "vets")
public Collection<Vet> updateVets() throws DataAccessException {
return vetRepository.findAll();
}
In my opinion an exernal service has to call the same methods.
来源:https://stackoverflow.com/questions/16235401/spring-cachable-updating-data