0
votes

I want to perform below Operations for Spring Cache.

  1. check if passed String exists in Cache or not. If exists just return true, if not there then add to cache; checkInCache(String str)

  2. evict the String from Cache evict(String str)

Tried like below

@Component public class FlightCache {

public static final Logger log = LoggerFactory.getLogger(FlightCache.class);

@Autowired
CacheManager cacheManager;

public boolean isFlightKeyPresent(final String flightKey) {
    final ValueWrapper existingValue = cacheManager.getCache("flightCache").get(flightKey);
    log.info("existingValueexistingValue " + existingValue);
    if (existingValue == null) {
        cacheManager.getCache("flightCache").put(flightKey, flightKey);
        return false;
    } else {
        return true;
    }
}

and added @EnableCaching annotation on configuration class.

ERROR:

 required a bean of type 'org.springframework.cache.CacheManager' that could not be found. The injection point has the following annotations:   - @org.springframework.beans.factory.annotation.Autowired(required=true)Action:Consider defining a bean of type 'org.springframework.cache.CacheManager' in your configuration.
1
Please go through this tutorial - R.G

1 Answers

0
votes
  1. To check for cache contains key you can do this:

    @Autowired CacheManager cacheManager;

    boolean isKeyPresent(Object key) { cacheManager.getCache("MyCacheName").get(key) != null; }

  2. To evict key you can do this:

    @Autowired CacheManager cacheManager;

    boolean cacheEvict(Object key) { cacheManager.getCache("MyCacheName").evictIfPresent(key); }