簡體   English   中英

Spring Cache從值中獲取鍵

[英]Spring Cache get key from the Value

我已經在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;

}

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

我尚未測試代碼段,但是,希望您能理解。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM