弹簧缓存没有从 Map 中检索值,尽管它存在



我正在尝试在运行时将数据添加到缓存中并检索它。我能够成功地将数据添加到 HashMap 中,但是当我调用 findbyIndex 方法时,尽管键存在于 Map 中,但我得到了空值。下面是代码:

import java.util.HashMap;
import java.util.Map;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;
@Component
@CacheConfig(cacheNames = { "cachetest" })
public class CacheService {
   private static Map<String, String> store = new HashMap<String, String>();
   @CachePut
   public void putData(String dataid, String data) {
      System.out.println("Executing put data...");
      store.put(dataid, data);
   }
   @Cacheable
   public String findByIndex(String dataid) {
      System.out.println(":Executing findByIndex ...");
      for (Map.Entry<String, String> entry : store.entrySet()) {
         System.out.println(entry.getKey() + " : " + entry.getValue());
      }
      return store.get(dataid);
   }
}

我的 ehcache.xml 对于这个缓存配置是:

<cache alias="cachetest">
        <expiry>
            <ttl unit="seconds">5</ttl>
        </expiry>
        <heap unit="entries">1500</heap>
        <jsr107:mbeans enable-statistics="true" />
    </cache>

缓存配置文件:

import java.util.Arrays;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.concurrent.ConcurrentMapCache;
import org.springframework.cache.support.SimpleCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@EnableCaching
public class CachingConfig {
   @Bean
   public CacheService customerDataService() {
       return new CacheService();
   }
   @Bean
   public CacheManager cacheManager() {
       SimpleCacheManager cacheManager = new SimpleCacheManager();
       cacheManager.setCaches(Arrays.asList(
         new ConcurrentMapCache("cachetest")));
       return cacheManager;
   }
}

当使用 putData 方法将新值添加到存储地图时,该值已成功添加到 HashMap 中,但是如果我尝试通过调用 findByIndex 方法来获取新添加的数据的值,该方法将返回空值,尽管它存在。知道下面发生了什么吗?

问题是对@CachePut行为的错误期望。正如您在文档中读到的那样,注释将使用方法参数来计算缓存键,并使用方法返回值来计算缓存值。

因此,您需要重新设计方法的注释或签名的使用。

最新更新