Versions of Ehcache before version 2.5 allowed any number of CacheManagers with the same name (same configuration resource) to exist in a JVM. Ehcache 2.5 and higher does not allow multiple CacheManagers with the same name to exist in the same JVM. CacheManager() constructors creating non-Singleton CacheManagers can violate this rule 在Ehcache版本2.5之后,同样的名字只能创建一个,除了shiro之外还有其他使用了EhCache,因此会报错。
1. 降低EhCache版本(网上已有解决办法)
<dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache-core</artifactId> <version>2.4.8</version> </dependency>2. 在代码中判断是否已经存在CacheManager实例,如果存在直接使用,不存在则创建(通过查看EhCacheManager代码可以分析出来) 例如:
/** * 缓存管理器 * 可能已经存在CacheManager,在ehcache-core 2.5版本之后再次创建CacheManager会失败 * @return */ @Bean public EhCacheManager ehCacheManager() { CacheManager cacheManager = CacheManager.getCacheManager("es"); if(cacheManager == null){ try { cacheManager = CacheManager.create(ResourceUtils.getInputStreamForPath("classpath:config/ehcache-shiro.xml")); } catch (IOException e) { throw new RuntimeException("initialize cacheManager failed"); } } EhCacheManager ehCacheManager = new EhCacheManager(); ehCacheManager.setCacheManager(cacheManager); return ehCacheManager; }