shiro与ehcache整合
上一篇文章写了shiro与springMVC的整合,这次说一下shiro与ehcace整合,首先要提出我们的第一个问题,为什么需要与ehcache进行整合,原因是 我们每去访问一个页面,shiro都去看你有没有这个权限,有的话,才会给你授权去访问这个页面的资源,就是这个部分,可是我们每访问一个页面,每次都要去获取一下他的所有权限,效率不高,而且用户的权限,不容易改变。所以就想到了缓存机制,我只要去读一遍,然后存到缓存中,其他的时候,去缓存中拿这个权限就可以了,那我们现在开始来整合他们吧!
/**
* 授权
* @param principals
* @return
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
User user = (User) principals.getPrimaryPrincipal();
List<Role> roleList = userService.findRolesByUserId(user.getId());
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
for(Role role : roleList){
info.addRole(role.getRoleName());
info.addStringPermissions(role.getPermList());
}
return info;
}
1.添加ehcache的jar包,,如果是maven项目,添加maven依赖
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache-core</artifactId>
<version>2.6.2</version>
</dependency>
2.创建 ehcache-shiro配置文件
<ehcache updateCheck="false" name="shiroCache">
<defaultCache
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="false"
diskPersistent="false"
diskExpiryThreadIntervalSeconds="120"
/>
</ehcache>
3.在shiro配置文件中引入ehcache
4.如果你在某个地方修改了用户的权限,想更新shiro中的权限,可以在shiroDb中使用下图方法,来清除shiro中的缓存
public void clearAllCachedAuthorizationInfo() {
getAuthorizationCache().clear();
}
public void clearAllCachedAuthenticationInfo() {
if(getAuthenticationCache() != null){
getAuthenticationCache().clear();
}
}