admin 管理员组

文章数量: 888526

Shiro的缓存

1.在自定义realm的doGetAuthorizationInfo方法,添加一个输出语句 

    @Overrideprotected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
//        获取当前已经登录用户的用户名String uname = (String) principalCollection.iterator().next();Set<String> permissions = userMapper.querypermission(uname);Set<String> roles = userMapper.queryrole(uname);SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();simpleAuthorizationInfo.setStringPermissions(permissions);simpleAuthorizationInfo.setRoles(roles);System.out.println("角色是"+roles);System.out.println("权限是"+permissions);
//        将权限信息返回权限管理器return simpleAuthorizationInfo;}

 发现 查询角色和权限信息执行了多次

 原因是每一个shiro标签都会执行一次权限查询,这对数据库的压力太大了,可以设置一个缓存,在用户登录之后,第一次查询出权限和 角色后,放入到缓存中,后面再需要,就从缓存中获取,不读取数据库。

 1.添加缓存依赖

     <dependency><groupId>net.sf.ehcache</groupId><artifactId>ehcache</artifactId></dependency><dependency><groupId>org.apache.shiro</groupId><artifactId>shiro-ehcache</artifactId><version>1.4.0</version></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency>

2.配置缓存策略

在resouce目录下,创建一个xml文件,名字随便起,一般叫ehcache.xml

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi=""dynamicConfig="false"updateCheck="false"><!--如果内存满了,会存储在这个内容-->
<!--    <diskStore path="c:\Temp"/>--><!--    name随便起,timetoliveseconds存活时间    maxentrites最大的条数--><!--    eternal是否永久存储   timeToIdleSeconds允许空闲多久的数据被删除--><!--    eternal="true" 表示常驻缓存--><!--    overflowToDisk="false" 缓存数据太多了,不向磁盘存储,而是清除老的数据--><defaultCachename="defaultCache"maxElementsInMemory="10000"eternal="false"timeToIdleSeconds="120"timeToLiveSeconds="120"overflowToDisk="false"maxElementsOnDisk="100000"diskPersistent="false"memoryStoreEvictionPolicy="LRU"/><!--memoryStoreEvictionPolicy 缓存的淘汰策略,最近最少使用  fifo最老数据-->
</ehcache>

3.在securityManager添加自定义的缓存

  // 配置缓存管理@Beanpublic EhCacheManager getehacche() {EhCacheManager ehCacheManager = new EhCacheManager();ehCacheManager.setCacheManagerConfigFile("classpath:ehcache.xml ");return ehCacheManager;}
    @Beanpublic DefaultWebSecurityManager getdefaultWebSecurityManager() {DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();defaultWebSecurityManager.setRealm(GetMyRealm1());defaultWebSecurityManager.setCacheManager(getehacche());return defaultWebSecurityManager;}

4.再次进行登录时:

 只查询一次了

本文标签: Shiro的缓存