我正在使用Spring和MyBatis的EhCache,并需要对EhCache的工作方式进行澄清。我有以下用于ehcache的配置文件。
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
updateCheck="false"
monitoring="autodetect"
dynamicConfig="true">
<diskStore path="java.io.tmpdir" />
<defaultCache maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="300"
timeToLiveSeconds="600"
diskSpoolBufferSizeMB="30"
maxElementsOnDisk="10000"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU" statistics="false">
</defaultCache>
</ehcache>
我只配置了默认缓存。如果我理解正确的话,当你在MyBatis mapper文件中添加这行代码时会创建一个新的缓存。
<cache type="org.mybatis.caches.ehcache.EhcacheCache" />
这让我想知道它是否继承默认缓存的属性?如果不是,那么配置默认缓存的目的是什么?
是为每个功能/数据创建一个缓存还是一个大型缓存最佳实践?
此外,我正在试图摆脱 XML,所以我想知道是否可以使用 Java Config 来完成所有这些工作?
我有以下 Java Config,但似乎没有办法使用 Java Config 方法配置默认缓存,所以我想知道它能否很好地与 MyBatis 协同工作,是否是个不错的选择?
@Configuration
@EnableCaching
public class CacheConfig implements CachingConfigurer {
@Autowired
Environment environment;
@Bean(destroyMethod = "shutdown")
public net.sf.ehcache.CacheManager ehCacheManager() {
CacheConfiguration cacheConfiguration = new CacheConfiguration();
cacheConfiguration.setName(environment.getRequiredProperty("ehcache.name"));
cacheConfiguration.setMemoryStoreEvictionPolicy(environment.getRequiredProperty("ehcache.memoryStoreEvictionPolicy"));
cacheConfiguration.setDiskExpiryThreadIntervalSeconds(environment.getRequiredProperty("ehcache.diskExpiryThreadIntervalSeconds", Integer.class));
cacheConfiguration.setDiskSpoolBufferSizeMB(50);
cacheConfiguration.setOverflowToDisk(true);
cacheConfiguration.setDiskPersistent(true);
cacheConfiguration.setMaxBytesLocalHeap("512000000");
cacheConfiguration.setMaxBytesLocalDisk("2048000000");
cacheConfiguration.eternal(false);
cacheConfiguration.setTimeToIdleSeconds(1800);
cacheConfiguration.setTimeToLiveSeconds(3600);
cacheConfiguration.statistics(true);
cacheConfiguration.logging(true);
net.sf.ehcache.config.Configuration config = new net.sf.ehcache.config.Configuration();
config.addCache(cacheConfiguration);
return net.sf.ehcache.CacheManager.newInstance(config);
}
@Bean
@Override
public org.springframework.cache.CacheManager cacheManager() {
return new EhCacheCacheManager(ehCacheManager());
}
@Override
public CacheResolver cacheResolver() {
return new SimpleCacheResolver();
}
@Override
public KeyGenerator keyGenerator() {
return new SimpleKeyGenerator();
}
@Override
public CacheErrorHandler errorHandler() {
return new SimpleCacheErrorHandler();
}
}