2017-07-27 80 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