shiro与ehcache整合

本文探讨如何通过整合Shiro与Ehcache提高权限管理效率,避免重复获取用户权限,介绍缓存机制在权限验证中的应用,包括添加Ehcache依赖、配置缓存策略及清除缓存的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

上一篇文章写了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();
		}
	}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值