java - Spring Cache 从 Value 中获取 key
问题描述
我在 Spring Boot 应用程序中使用了 Spring 缓存来针对某个键存储值。我现在有了值,是否可以根据值从缓存中获取密钥?如果是这样请帮助。
我尝试使用有关net.sf.ehcache.Cache
但由于某种原因它没有显示任何导入建议并给出错误net.sf.ehcache.Cache cannot be resolve to a type 的解决方案。我是弹簧缓存的新手,所以不知道该怎么做。
我项目中的依赖项是
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>org.ehcache</groupId>
<artifactId>ehcache</artifactId>
</dependency>
<dependency>
<groupId>javax.cache</groupId>
<artifactId>cache-api</artifactId>
</dependency>
我正在使用的代码是
public String getEmailByOtp(String otp)
{
String email = "";
Ehcache cache = (Ehcache) CacheManager.getCache("otpCache").getNativeCache();
for (Object key: cache.getKeys()) {
Element element = cache.get(key);
if (element != null) {
Object value = element.getObjectValue(); // here is the value
if(value.equals(otp)) {
email = key.toString();
}
}
}
return email;
}
解决方案
Spring Cache和EhCache是两种完全不同的缓存机制实现。虽然有一种方法可以将基于 Spring 的缓存转换为基于 EhCache 的缓存,但这并不意味着 Spring 自动提供了它的实现。您必须导入 EhCache 库(使用 Maven、Gradle 等)。
干得好。您将获得一个net.sf.ehcache.EhCache
包含 Spring 中所有缓存区域的实例org.springframework.cache.CacheManager
。
EhCache cache = (EhCache) CacheManager.getCache("myCache").getNativeCache();
然后,不可能像使用Map
. 遍历键并获取与键匹配的特定元素。这样,您也可以遍历所有值。
for (Object key: cache.getKeys()) {
Element element = cache.get(key);
if (element != null) {
Object value = element.getObjectValue(); // here is the value
}
}
我还没有测试过这些片段,但是,我希望你能明白。
推荐阅读
- reactjs - 如何将多个参数传递给事件的咖喱函数
- javascript - 选择新容器时暂停容器内的音频
- javascript - JS/ 将一个类方法导入另一个类
- ruby - 是否有一种 Ruby 方法可以以易于阅读的方式将对象打印到控制台?
- c++ - 如何通过.so强制链接到静态库?
- python - 如何为搜索功能修复基本的 Spotipy“TypeError:+: 'set' 和 'str' 不支持的操作数类型”?
- angularjs - 玉模板中的ng-repeat注释掉了
- c++ - C++ 按值排序 unordered_map 或 map
- bash - 如何从批处理脚本中的文本文件中找到以下文本?
- github - 神秘的 Azure Pipelines 定义出现在我的 github 存储库中