【问题标题】:Store a String in Spring Cache and evict在 Spring Cache 中存储一个字符串并逐出
【发布时间】:2021-04-22 10:05:51
【问题描述】:

我想为 Spring Cache 执行下面的操作。

  1. 检查传递的字符串是否存在于缓存中。如果存在则返回true,如果不存在则添加到缓存; checkInCache(String str)

  2. 从缓存中驱逐字符串 逐出(字符串 str)

尝试如下

@组件 公共类 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;
    }
}

并在配置类上添加@EnableCaching注解。

错误:

 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.

【问题讨论】:

标签: spring spring-cache


【解决方案1】:
  1. 要检查缓存是否包含键,您可以这样做:

    @自动连线 CacheManager 缓存管理器;

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

  2. 要驱逐密钥,您可以这样做:

    @自动连线 CacheManager 缓存管理器;

    boolean cacheEvict(对象键) { cacheManager.getCache("MyCacheName").evictIfPresent(key); }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-10-12
    • 1970-01-01
    • 2018-09-23
    • 2020-07-05
    • 1970-01-01
    • 1970-01-01
    • 2022-10-23
    • 1970-01-01
    相关资源
    最近更新 更多