如何解决在 Spring Cache 中存储一个字符串并驱逐
我想为 Spring Cache 执行以下操作。
-
检查传递的字符串是否存在于缓存中。如果存在则返回true,如果不存在则添加到缓存; checkInCache(String str)
-
从缓存中驱逐字符串 驱逐(字符串 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.
解决方法
-
要检查缓存是否包含密钥,您可以这样做:
@Autowired CacheManager cacheManager;
boolean isKeyPresent(Object key) { cacheManager.getCache("MyCacheName").get(key) != null; }
-
要驱逐密钥,您可以这样做:
@Autowired CacheManager cacheManager;
boolean cacheEvict(Object key) { cacheManager.getCache("MyCacheName").evictIfPresent(key); }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。