Spring boot添加shiro时,添加EhCacheManager出错

来源:互联网 发布:php 图片上传插件 编辑:程序博客网 时间:2024/05/17 22:19

错误代码 :

org.apache.shiro.cache.CacheException: net.sf.ehcache.CacheException: Another unnamed CacheManager already exists in the same VM. Please provide unique names for each CacheManager in the config or do one of following:1. Use one of the CacheManager.create() static factory methods to reuse same CacheManager with same name or create one if necessary2. Shutdown the earlier cacheManager before creating new one with same name.

原因分析:

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;    }
原创粉丝点击