Shiro支持很多第三方缓存工具。官方提供了shiro-ehcache,实现了把EHCache当做Shiro的缓存工具的解决方案。其中最好用的一个功能是就是缓存认证执行的Realm方法,减少对数据库的访问。
1 添加依赖
添加shiro-ehcache依赖。
commons-io主要是为了使用里面的工具类。本质和当前整合功能没有关系。
<dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-ehcache</artifactId> <version>1.4.2</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.6</version> </dependency>
2 编写ehcache缓存配置
在resources下新建ehcache/ehcache-shiro.xml
<?xml version="1.0" encoding="UTF-8"?> <ehcache name="ehcache" updateCheck="false"> <!-- 磁盘缓存位置 --> <diskStore path="java.io.tmpdir"/> <!-- 默认缓存 --> <defaultCache maxEntriesLocalHeap="1000" eternal="false" timeToIdleSeconds="3600" timeToLiveSeconds="3600" overflowToDisk="false"> </defaultCache> <!-- 登录记录缓存 锁定10分钟 --> <cache name="loginRecordCache" maxEntriesLocalHeap="2000" eternal="false" timeToIdleSeconds="600" timeToLiveSeconds="0" overflowToDisk="false" statistics="true"> </cache> </ehcache>
3 修改配置文件
@Bean public DefaultWebSecurityManager securityManager() { DefaultWebSecurityManager manager = new DefaultWebSecurityManager(); HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher(); hashedCredentialsMatcher.setHashAlgorithmName("md5"); hashedCredentialsMatcher.setHashIterations(2); myRealm.setCredentialsMatcher(hashedCredentialsMatcher); manager.setRealm(myRealm); manager.setRememberMeManager(rememberMeManager()); manager.setCacheManager(getEhCacheManager()); return manager; } @Bean public EhCacheManager ehCacheManager(){ EhCacheManager ehCacheManager = new EhCacheManager(); InputStream is = null; try { is = ResourceUtils.getInputStreamForPath("classpath:ehcache/ehcache-shiro.xml"); } catch (IOException e) { e.printStackTrace(); } net.sf.ehcache.CacheManager cacheManager = new net.sf.ehcache.CacheManager(is); ehCacheManager.setCacheManager(cacheManager); return ehCacheManager; }