我正在尝试在运行时将数据添加到缓存中并检索它。我能够成功地将数据添加到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);
}
}
此cacheconfig的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值尽管它存在。有什么想法发生在下面吗?
答案 0 :(得分:0)
问题是对@CachePut
行为的错误预期。正如您可以阅读in the documentation一样,注释将使用方法参数来计算缓存键和方法返回值来计算缓存值。
因此,您需要重复使用注释或方法的签名。