问题
Let's imagine that I have a method which can updates one field for all entities.
public void makeAllCarsRed(){...}
I know that Spring offers 3 annotation to manage cache:
@Cacheable- tries to find value in cache. If cannot find - execute method and adds to cache;@CachEvict- just remove objects from cache by criteria;@CachPut- put new value to cache
I don't see a way to apply these annotations for my situation.
P.S.
I think that it is too expensive to invalidate all cach
回答1:
Spring caches a whole entity, not a single field. So you cannot evict a field from the cache.
If you would want to evict the entities from the cache, you would also have aproblem, but that can be solved :
Outside your method it is not visible, which entites are updated, so you cannot use any of these annotations.
What you can do, is get the CacheManager injected into the class that owns the method makeAllCarsRed() and than update the cache manually for all entites that are updated :
in your config
@Bean
public CacheManager cacheManager() {
return new ConcurrentMapCacheManager("cacheName");
}
class that has makeAllCarsRed() :
public class MakeAllCarsRedService{
@Autowired CacheManager cm;
...
public void makeAllCarsRed(){
Cache cache = cm.getCache("cacheName");
//remove from cache
cache.evict(key)
//or, if neddec add to cache
put(key, entity);
...
}
}
来源:https://stackoverflow.com/questions/35826385/how-to-update-spring-cache-partialllyone-field-onlywhen-object-mutates