简体   繁体   中英

Spring Cache get key from the Value

I have used spring cache in a spring boot application to store value against a certain key. I now have the value, is it possible to get the key from cache against the value? If so Please help.

I tried using solutions regarding net.sf.ehcache.Cache but for some reason it doesn't show any import suggestions and gives error net.sf.ehcache.Cache cannot be resolved to a type . I am new to spring cache so have no clue what to do further.

The dependencies in my project are

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

The code I am using is

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 Cache and EhCache are two completely different implementations of caching mechanisms. Although there is a way to cast Spring-based cache to EhCache-based one, it doesn't mean Spring provides automatically its implementation. You have to import the EhCache library (using Maven, Gradle, etc.).

Here you go. You get an instance of net.sf.ehcache.EhCache which contains all the cache regions from Spring org.springframework.cache.CacheManager .

EhCache cache = (EhCache) CacheManager.getCache("myCache").getNativeCache();

Then, it's not possible to access all the values directly like with the Map . Iterate through the keys and get the particular elements matching the key. This way you iterate through all the values as well.

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

I haven't tested the snippets, however, I hope you get the idea.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM