1

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
  • since cache contains just a subset of your entities you will have to change the entities in DB and invalidate your cache.
    – devops
    Commented Mar 6, 2016 at 21:45

2 Answers 2

2

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);
...
}
}
1

A cached method do not return a deep copy of the cache content so you can make side effects on it. Let getCars(boolean) be your cached method:

@Cacheable("cars")
public List<Car> getCars(boolean isAvailable) {
    return ...;
}

Call your cached method with the right parameters and then corrupt the cache:

public void makeAllCarsRed() {
    List<Car> cache = getCars(true);

    for (Car carInCache : cache) {
        carInCache.setColor("red");
    }
}

The next time you will call getCars(boolean), it will return the updated cache.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.