【问题标题】:spring cache not retrieving the value from Map though it exist尽管存在,但弹簧缓存没有从 Map 中检索值
【发布时间】:2018-01-16 22:30:05
【问题描述】:

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

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 方法获取新添加的数据的值,该方法虽然返回 null 值存在。知道下面发生了什么吗?

【问题讨论】:

    标签: spring ehcache spring-cache


    【解决方案1】:

    问题是对@CachePut 行为的错误预期。如您所见in the documentation,注解将使用方法参数来计算缓存键,并使用方法返回值来计算缓存值。

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

    【讨论】:

      猜你喜欢
      • 2020-07-06
      • 2015-12-01
      • 2012-07-07
      • 1970-01-01
      • 2018-10-24
      • 1970-01-01
      • 1970-01-01
      • 2018-03-09
      • 2012-07-11
      相关资源
      最近更新 更多