springboot項目中,ehcache報錯,需要CacheManager單例的解決辦法


在新的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);
    }

}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM