我的要求是擁有基於磁盤的緩存。如果緩存內存已滿,我需要將LRU元素推送到磁盤。然後如果磁盤上的文件已滿,那麼我希望磁盤上的LRU元素被驅逐。這是非常簡單的要求,但是我無法使用EhCache實現此目的。EhCache永遠不會像預期的那樣運行
我有以下的配置利用了Ehcache(2.10.1)的:
<defaultCache name="default"
maxBytesLocalHeap="50m"
maxBytesLocalDisk="100g"
eternal="true"
timeToIdleSeconds="0"
timeToLiveSeconds="0"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU">
<persistence strategy="localTempSwap"/>
</defaultCache>
我期待在這裏,當緩存被填滿(即緩存大小超過50M),我想LRU元素(S )被推送到文件,因此在內存中爲新元素創建一些空間。
然而,這不是的Ehcache是如何工作的,我做了一個樣本測試,以檢查元素計數緩存:
公共靜態無效的主要(字串[] args)拋出異常{
ArrayList<String> keys = new ArrayList<String>();
CacheManager cacheManager;
FileInputStream fis = null;
try {
fis = new FileInputStream(
new File("src/config/ehcache.xml").getAbsolutePath());
cacheManager = CacheManager.newInstance(fis);
}
finally {
fis.close();
}
java.lang.Runtime.getRuntime().addShutdownHook(new Thread(){
@Override
public void run() {
try
{
System.out.println("Shutting down Eh Cache manager !!");
cacheManager.clearAll();
cacheManager.shutdown();
System.out.println("done !!");
}catch(Exception e)
{
e.printStackTrace();
}
}
});
System.out.println("starting ...");
System.out.println(System.getProperty("java.io.tmpdir"));
cacheManager.addCache("work_item_111");
Cache ehCache = cacheManager.getCache("work_item_111");
long start_outer = System.currentTimeMillis();
for(int i =0;i<30;i++)
{
long start = System.currentTimeMillis();
String key = UUID.randomUUID().toString();
ehCache.put(new Element(key, getNextRandomString()));
keys.add(key);
//System.out.println("time taken : " + (System.currentTimeMillis()- start));
System.out.println((System.currentTimeMillis()- start) +" - " + (ehCache.getStatistics().getLocalDiskSizeInBytes()/1024/1024) + " - " +(ehCache.getStatistics().getLocalHeapSizeInBytes()/1024/1024));
}
System.out.println("time taken-total : " + (System.currentTimeMillis()- start_outer));
System.out.println(ehCache.getSize());
System.out.println("disk size : " +ehCache.getStatistics().getLocalDiskSizeInBytes()/1024/1024);
System.out.println("memory size : " +ehCache.getStatistics().getLocalHeapSizeInBytes()/1024/1024);
Iterator<String> itr = keys.iterator();
int count =0;
while(itr.hasNext())
{
count++;
String key = itr.next();
if(ehCache.get(key) == null)
{
System.out.println("missingg key : " + key);
}
}
System.out.println("checked for count :" + count);
}
結果是相當令人失望的,在將30個元素放入緩存之後(每個元素的大小約爲4mb),我只能看到7個元素在緩存中(ehCache.getSize()返回7),也沒有看到文件在磁盤上增長。
如果我在這裏丟失任何東西,任何EhCache專家都可以幫助我嗎?謝謝。
謝謝!我認爲它不符合我的要求,因爲我無法控制數據放入ehcache的速度。我需要的是溢出模型,除非最低層(磁盤)已滿,否則不會丟失數據。 – abhi