首页 > 解决方案 > 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;

}

标签: javaspringspring-bootehcachespring-cache

解决方案


Spring CacheEhCache是两种完全不同的缓存机制实现。虽然有一种方法可以将基于 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
    }
}

我还没有测试过这些片段,但是,我希望你能明白。


推荐阅读