2017-07-27 131 views
0

我想在春天使用Echcache mvc。因此對於此使用類似於此的java配置:Spring mvc Ehcache問題

public net.sf.ehcache.CacheManager ehCacheManager() { 
    net.sf.ehcache.config.Configuration config = new net.sf.ehcache.config.Configuration(); 
    CacheConfiguration cacheConfig = new CacheConfiguration(); 
    cacheConfig.setName("test"); 
    cacheConfig.setMaxEntriesLocalHeap(0); 
    cacheConfig.setMaxEntriesLocalDisk(10); 
    cacheConfig.setTimeToLiveSeconds(500); 
    config.addCache(cacheConfig); 
    DiskStoreConfiguration diskStoreConfiguration = new DiskStoreConfiguration(); 
    diskStoreConfiguration.setPath("C:/MyCache1"); 
    config.addDiskStore(diskStoreConfiguration); 
    return net.sf.ehcache.CacheManager.newInstance(config); 
} 

並用於註解@cachable用於高速緩存。它工作正常。但所有緩存的數據都保存在內存中。它只創建零大小的test.data文件。現在我的問題是如何將緩存數據寫入磁盤?

回答

2

添加以下設置磁盤存儲:

cacheConfig.setDiskPersistent(真);

public net.sf.ehcache.CacheManager ehCacheManager() { 
    net.sf.ehcache.config.Configuration config = new 
    net.sf.ehcache.config.Configuration(); 
    CacheConfiguration cacheConfig = new CacheConfiguration(); 
    cacheConfig.setName("test"); 
    cacheConfig.setMaxEntriesLocalHeap(0); 
    cacheConfig.setMaxEntriesLocalDisk(10); 
    cacheConfig.setTimeToLiveSeconds(500); 
    cacheConfig.setDiskPersistent(true); 
    config.addCache(cacheConfig); 
    DiskStoreConfiguration diskStoreConfiguration = new 
    DiskStoreConfiguration(); 
    diskStoreConfiguration.setPath("C:/MyCache1"); 
    config.addDiskStore(diskStoreConfiguration); 
    return net.sf.ehcache.CacheManager.newInstance(config); 
} 
  • 注意:此方法現在是@Deprecated,並已被替換爲持久性(PersistenceConfiguration)方法。
+0

謝謝,我使用'config.persistence(新的PersistenceConfiguration()。strategy(PersistenceConfiguration.Strategy.LOCALTEMPSWAP));'但不工作。 – ali

+1

Strategy.LOCALTEMPSWAP僅用於內存中緩存。如果您想要基於磁盤文件,請使用Strategy.LOCALRESTARTABLE - 注意:LOCALRESTARTABLE持久性功能在企業版Ehcache中可用。 –

+0

那麼爲什麼我不使用彈簧提供程序'ehcache'它寫入磁盤?我的意思是使用'ehcache'方法 – ali

1

正如其他答案中所述,您需要使緩存本身使用磁盤層。 cacheConfig.persistence(new PersistenceConfiguration().strategy(PersistenceConfiguration‌​.Strategy.LOCALTEMPS‌​WAP)); 如您在您的評論指出:

如果您使用的是最新的Ehcache 2.X版本,這應該被完成。 請注意,此選項是非防碰撞磁盤層,而選項Strategy.LOCALRESTARTABLE確實處理崩潰,但只能在企業版中使用。

但是,以上是不夠的,你需要在應用程序關閉時正確關閉緩存和緩存管理器。這將導致所有條目被刷新並創建索引文件。沒有這些,數據將在重新啓動時被丟棄。

+0

謝謝,我的問題解決了,重新啓動應用程序後,它創建'.index'文件和'.data '文件。但是在'setTimeToLiveSeconds'到期之後,它會刪除一個創建新文件。所以你認爲'setTimeToLiveSeconds'是合理的30天或不合理?以及如何處理這個問題?謝謝。 – ali