Spring Cache从值中获取键

时间:2018-07-17 16:18:02

标签: java spring spring-boot ehcache spring-cache

我已经在spring boot应用程序中使用spring缓存来存储某个键的值。我现在有了值,是否可以根据值从缓存中获取密钥?如果是这样,请帮助。

我尝试使用有关net.sf.ehcache.Cache的解决方案,但由于某种原因,它没有显示任何导入建议,并给出了错误 net.sf.ehcache.Cache无法解析为类型。我是Spring缓存的新手,所以不知道该怎么做。

我项目中的依赖项是

<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;

}

1 个答案:

答案 0 :(得分:2)

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
    }
}

我还没有测试过这些代码段,但是,我希望你能理解。