在spring-xml配置文件中,我们配置了缓存开启:
<!-- 缓存管理 -->
<bean id="shiroCacheManager" class="org.apache.shiro.cache.MemoryConstrainedCacheManager"></bean>
<!--
使用Shiro自带的JdbcRealm类
指定密码匹配所需要用到的加密对象
指定存储用户、角色、权限许可的数据源及相关查询语句
-->
<bean id="jdbcRealm" class="org.apache.shiro.realm.jdbc.JdbcRealm">
<!--<property name="credentialsMatcher" ref="credentialsMatcher"></property>-->
<property name="permissionsLookupEnabled" value="true"></property>
<property name="dataSource" ref="dataSource"></property>
<property name="authenticationQuery"
value="SELECT password FROM base_user WHERE login_name = ?"></property>
<property name="userRolesQuery"
value="SELECT t.role_code from base_role t left join base_user tt on t.ROLE_CODE=tt.DEFAULT_ROLE_CODE WHERE LOGIN_NAME = ? "></property>
<property name="permissionsQuery"
value="SELECT PT.PERMISSION_NAME from PERMISSION_WITH pw LEFT JOIN PERMISSION_TEST pt on pw.P_ID = pt.PERMISSION_ID LEFT JOIN BASE_ROLE t on t.ROLE_ID = pw.ROLE_ID where t.role_code = ?"></property>
</bean>
<!-- Shiro安全管理器 -->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<!--获取权限源,可以通过获取数据库也可以redis-->
<property name="realm" ref="jdbcRealm"></property>
<property name="cacheManager" ref="shiroCacheManager"></property>
</bean>
通过shiroCacheManager,可以极大的提升性能,不用每次都去数据库获取权限信息,以下就是在controller中更新缓存的方法:
@RequestMapping(value="/clearShiroCatch",method= RequestMethod.GET)
@ResponseBody
public void clearShiroCatch(){
//获取权限看一下
/*
/* @Autowired
private MemoryConstrainedCacheManager shiroCacheManager;
*/
Cache<Object, Object> cache = shiroCacheManager.getCache("org.apache.shiro.realm.jdbc.JdbcRealm.authorizationCache");
// shiroCacheManager.destroy();//清除全部缓存
// LifecycleUtils.destroy(cache);//清除某个缓存
Subject subject = SecurityUtils.getSubject();
/*subject.getPrincipal()------>登录名
String realmName = subject.getPrincipals().getRealmNames().iterator().next();
//第一个参数为用户名,想要操作权限的用户,第二个参数为realmName,
SimplePrincipalCollection principals = new SimplePrincipalCollection(subject.getPrincipal(),realmName);
*/
RealmSecurityManager securityManager =
(RealmSecurityManager) SecurityUtils.getSecurityManager();
JdbcRealm jdbcRealm = (JdbcRealm)securityManager.getRealms().iterator().next();
//删除登陆人
jdbcRealm.getAuthorizationCache().remove(subject.getPrincipal());
//删除登陆人对应的缓存
jdbcRealm.getAuthorizationCache().remove(subject.getPrincipals());
//重新加载subject
subject.releaseRunAs();
}