在新的springboot項目中,如果在mybatis中使用了ehcache后,再第二次使用ehcache,會提示錯誤
Another CacheManager with same name 'default' already exists in the same VM. Please provide unique names for each CacheManager in the config or do one of following:
原因是在ehcache2.5版本后,cachemanager必須是單例的,不允許多次創建。
解決辦法
在config的配置文件中,新建一個bean,然后署名,在程序引用他時,標注這個name為新建的cachemanager
配置代碼
@Configuration public class EhCacheConfig { // @Bean // public CacheManager getCacheManager() { // // return CacheManager.create("classpath:ehcache.xml"); // } @Bean(name = "demo") public CacheManager getCacheManagerDemo() { return CacheManager.create("classpath:ehcache2.xml"); } }
ehcache2.xml ( ehcache.xml文件為系統默認加載的額,這里必須另建一個xml文件,以示區分 )
<?xml version="1.0" encoding="UTF-8"?> <ehcache name="demo" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd" updateCheck="false"> <!-- xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd" --> <!-- 磁盤保存路徑 --> <diskStore path="D:\44test\ehcache" /> <defaultCache maxElementsInMemory="1000" maxElementsOnDisk="10000000" eternal="false" overflowToDisk="true" timeToIdleSeconds="120" timeToLiveSeconds="120" diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU"> </defaultCache> </ehcache>
引用部分
在service層
@Cacheable(cacheManager = "demo") public List<User> queryAll() { // TODO Auto-generated method stub return this.userMapper.queryAll(); }
啟動入口類
@SpringBootApplication @MapperScan(basePackages = {"cn.taotao.dao"}) @EnableCaching public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }