【问题标题】:Spring Cache get key from the ValueSpring Cache 从 Value 中获取 key
【发布时间】:2018-07-17 16:18:01
【问题描述】:

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

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

我项目中的依赖是

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

}

【问题讨论】:

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


    【解决方案1】:

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

    我还没有测试过 sn-ps,但是,我希望你明白。

    【讨论】:

    • 我尝试得到错误Cannot make a static reference to the non-static method getCache(String) from the type CacheManager 现在我自动连接 Cachemanager 以拥有它的对象...这是正确的方法吗?
    • 而下一个错误出现在 for 循环中,它向我显示 The method getKeys() is undefined for the type CacheProperties.EhCache
    • 我没有测试我的代码,我应该包含这些信息。首先,您不能混合静态和自动装配的内容。其次,检查库是否正确导入。 EhCache有这个方法:ehcache.org/apidocs/2.9/net/sf/ehcache/Ehcache.html#getKeys()
    • 我相信导入是正确的......自上周以来我缓存值的部分工作正常我希望我在导入时没有犯错,import org.springframework.boot.autoconfigure.cache.CacheProperties.EhCache; 这是我的导入在我的代码中有
    • 你需要net.sf.ehcache.EhCache
    猜你喜欢
    • 2017-09-12
    • 2013-09-22
    • 2014-09-06
    • 2015-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多