0
我使用的EHCache我的Spring应用程序,我不认为它的工作如预期的EHCache 3不工作的地图
如果你看到下面我添加相同的数据到一个HashMap和也Ehcache ..但是当我试图从ehCache中获得它时,它会打印出null
在初始化缓存或我错过的内容方面有什么问题吗?
我班
@Named
public class Myclass extends DataLoader {
private static final Logger LOGGER = Logger.getLogger(Myclass.class.getName());
@Inject
private DictionaryInitializer dictionaryLoader;
@Inject
@Named("fileLoader")
private FileLoader fileLoader;
private Cache<String,Object> dictionary;
@PostConstruct
@Override
public void loadResource() {
List<String> spellTerms = null;
dictionary=dictionaryLoader.getCache();
String fileName = "C:\\spelling.txt";
spellTerms = fileLoader.loadResource(fileName);
HashMap<String,Object> dictData = new HashMap<>();
for(String line:spellTerms)
{
for (String key : parseWords(line))
{
HashMap<String,Object> tempMap = dictionaryUtil.indexWord(key);
if(tempMap!=null && !tempMap.isEmpty())
{
Set<Map.Entry<String, Object>> entries = tempMap.entrySet();
for(Map.Entry<String, Object> entry:entries)
{
dictionary.put(entry.getKey(), entry.getValue());
}
}
dictData.putAll(tempMap);
}
}
System.out.println(dictData.get("urcle")); //prints 45670
System.out.println(dictionary.get("urcle")); // prints null
}
private static Iterable<String> parseWords(String text)
{
List<String> allMatches = new ArrayList<String>();
Matcher m = Pattern.compile("[\\w-[\\d_]]+").matcher(text.toLowerCase());
while (m.find()) {
allMatches.add(m.group());
}
return allMatches;
}
}
我DictionaryInitializer就像下面
public class DictionaryInitializer {
private static final Logger LOGGER = Logger.getLogger(DictionaryInitializer.class.getName());
private Cache<String,Object> dictionary;
@PostConstruct
public void initializeCache() {
CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
.build(true);
this.dictionary = cacheManager.createCache("myCache",
CacheConfigurationBuilder.newCacheConfigurationBuilder(String.class, Object.class,
ResourcePoolsBuilder.heap(100)).build());
LOGGER.info("Dictionary loaded");
}
public Cache<String,Object> getCache(){
return dictionary;
}
public void setCache(Cache<String,Object> dictionary) {
this.dictionary=dictionary;
}
}
héhé!小心缓存大小! –
小心。缓存不是地图。如果您正在读取应该永久存储在内存中的数据,那不是您想要的缓存。当感觉像缓存时,缓存可能会逐出并返回null(即使实际实现通常不会这样做)。所以如果你只想把数据保存在堆上,你需要一张地图。 – Henri