使用CacheManager:放入缓存的数据具有的特点是:查询多,增删改极少。因为当数据更新的时候,需要对缓存中的数据和数据库之间进行同步。
具体操作:
1.pom.xml导入依赖:
<!--引入shiro整合ehcache的依赖-->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-ehcache</artifactId>
<version>1.5.3</version>
</dependency>
2.在ShiroConfig.java(也就是shiro的配置文件)做如下配置
// 3.创建自定义realm
@Bean("realm")
public Realm getRealm()
{
TestRealm testRealm = new TestRealm();
// 设置 realm 使用hash凭证匹配器
HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
// 使用的算法
credentialsMatcher.setHashAlgorithmName("md5");
// 散列的次数
credentialsMatcher.setHashIterations(1024);
testRealm.setCredentialsMatcher(credentialsMatcher);
// 开启缓存管理
testRealm.setCacheManager(new EhCacheManager()); // 用 ehcache 做缓存
testRealm.setCachingEnabled(true); // 开启全局的缓存管理
testRealm.setAuthenticationCachingEnabled(true); // 开启认证缓存
testRealm.setAuthenticationCacheName("authenticationCache"); // 给认证缓存起别名
testRealm.setAuthorizationCachingEnabled(true); // 开启授权缓存
testRealm.setAuthorizationCacheName("authorizationCache"); // 给授权缓存起别名
return testRealm;
}