java - Spring Cache 从值中获取键

标签 java spring spring-boot ehcache spring-cache

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

我尝试使用有关 net.sf.ehcache.Cache 的解决方案,但由于某种原因它没有显示任何导入建议并给出错误 net.sf.ehcache.Cache cannot be resolved到一个类型。我是 spring 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;

}

最佳答案

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

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

关于java - Spring Cache 从值中获取键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51386082/

相关文章:

java - gradle生成protobuf类但显示编译错误

java - AJAX/Spring MVC - 没有 Spring Security 的 403 禁止错误

java - 从另一个类通知java线程

java - Spring Boot将带有时区的日期时间转换为服务器中的 '0'时区

java - 如何使用 RestTemplate 将上游错误响应传递给下游服务

java - 在Linux中删除环境变量末尾的尾随bin/java

Java 枚举在接口(interface)或类中的放置

java - 如何在焦点丢失和发送到服务器之前更改输入文本值

java - 使用自定义 validator 时忽略 spring 验证注释

java - 针对接口(interface)的 Autowiring 返回 null - Spring MVC