Java Spring缓存从值中获取密钥

Java Spring缓存从值中获取密钥,java,spring,spring-boot,ehcache,spring-cache,Java,Spring,Spring Boot,Ehcache,Spring Cache,我在spring引导应用程序中使用了spring缓存来存储某个键的值。我现在有了这个值,是否可以根据该值从缓存中获取密钥?如果是,请帮忙 我尝试使用有关net.sf.ehcache.Cache的解决方案,但由于某些原因,它没有显示任何导入建议,并给出错误net.sf.ehcache.Cache无法解析为类型。我是SpringCache的新手,所以不知道接下来要做什么 我的项目中的依赖项是 <dependency> <groupId>org.springfr

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

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

我的项目中的依赖项是

<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>
和是两种完全不同的缓存机制实现。尽管有一种方法可以将基于Spring的缓存转换为基于EhCache的缓存,但这并不意味着Spring会自动提供它的实现。您必须导入EhCache库(使用Maven、Gradle等)

给你。您将获得
net.sf.ehcache.ehcache
的一个实例,其中包含Spring中的所有缓存区域

然后,不可能像使用
映射
那样直接访问所有值。遍历键并获得与键匹配的特定元素。这样,您也可以迭代所有值

for (Object key: cache.getKeys()) {
    Element element = cache.get(key);
    if (element != null) {
        Object value = element.getObjectValue();     // here is the value
    }
}

我还没有测试代码片段,但是,我希望您能理解。

我尝试过,但得到的错误
无法从类型CacheManager中静态引用非静态方法getCache(String)
,现在我自动连接CacheManager使其对象。。。这是一种正确的方法吗?下一个错误是在for循环中,它向我显示了类型CacheProperties的方法getKeys()未定义。EhCache我还没有测试我的代码,我应该包括这些信息。首先,不能将静态内容和自动连线内容混用。其次,检查库是否正确导入。EhCache有这样的方法:我相信导入是正确的。。。我缓存值的部分工作正常,因为上周我希望我在导入时没有犯错误,
import org.springframework.boot.autoconfigure.cache.CacheProperties.EhCache这是我在代码中的导入,您需要
net.sf.ehcache.ehcache
EhCache cache = (EhCache) CacheManager.getCache("myCache").getNativeCache();
for (Object key: cache.getKeys()) {
    Element element = cache.get(key);
    if (element != null) {
        Object value = element.getObjectValue();     // here is the value
    }
}