How to update spring cache partiallly(one field only)?(when object mutates)

情到浓时终转凉″ 提交于 2019-12-25 07:35:58

问题


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:

  1. @Cacheable - tries to find value in cache. If cannot find - execute method and adds to cache;
  2. @CachEvict - just remove objects from cache by criteria;
  3. @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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!