目录
一、Shiro会话管理
1.1 分析tomcat会话管理与Shiro会话管理的区别
tomcat:用户第一次发送登录请求 ---> tomcat【将用户登录信息存入session】
用户第二次发送功能请求 ---> 验证tomcat的session中是否存在用户的登录信息;
Shiro会话管理:用户第一次发送登录请求 ---> 对应多个tomcat
问题:会存在访问不到用户信息的tomcat的情况;
解决方法:【将用户登录信息存在tomcat的一个共有的位置ehcache中】
用户第二次发送功能请求 ---> 验证ehcache缓存中是否存在用户登录信息;
画图理解:
结论:
Shiro的会话管理具备tomcat的会话管理的一切功能,
同时相较于tomcat的session,Shiro提供了对于分布式session的管理;
以上就是我们为什么要学习Shiro会话管理的原因;
1.2 Shiro会话管理的使用
1.2.1 实现SessionListener的监听器
MySessionListener
package com.leaf.ssm.shiro;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.SessionListener;
/**
* @author Leaf
* @site 2977819715
* @company 玉渊工作室
* @create 2022-08-29 9:42
*/
public class MySessionListener implements SessionListener {
@Override
public void onStart(Session session) {
//登录发请求时
System.out.println("MySessionListener.onStart 执行..."+session.getId());
}
@Override
public void onStop(Session session) {
//退出时执行
System.out.println("MySessionListener.onStop 执行..."+session.getId());
}
@Override
public void onExpiration(Session session) {
//session有效期到时
System.out.println("MySessionListener.onExpiration 执行..."+session.getId());
}
}
1.2.2 添加Spring-shiro的配置
① sessionManager
② cookie模板
applicationContext-shiro.xml
<!--注册安全管理器-->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="realm" ref="shiroRealm" />
<property name="sessionManager" ref="sessionManager"></property>
</bean>
<!-- Session ID 生成器 -->
<bean id="sessionIdGenerator" class="org.apache.shiro.session.mgt.eis.JavaUuidSessionIdGenerator">
</bean>
<!--sessionDao自定义会话管理,针对Session会话进行CRUD操作-->
<bean id="customSessionDao" class="org.apache.shiro.session.mgt.eis.MemorySessionDAO">
<property name="sessionIdGenerator" ref="sessionIdGenerator"/>
</bean>
<!--会话监听器-->
<bean id="shiroSessionListener" class="com.leaf.ssm.shiro.MySessionListener"/>
<!--会话cookie模板-->
<bean id="sessionIdCookie" class="org.apache.shiro.web.servlet.SimpleCookie">
<!--设置cookie的name-->
<constructor-arg value="shiro.session"/>
<!--设置cookie有效时间 永不过期-->
<property name="maxAge" value="-1"/>
<!--设置httpOnly 防止xss攻击: cookie劫持-->
<property name="httpOnly" value="true"/>
</bean>
<!--SessionManager会话管理器-->
<bean id="sessionManager" class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager">
<!--设置session会话过期时间 毫秒 2分钟=120000-->
<property name="globalSessionTimeout" value="120000"/>
<!--设置sessionDao-->
<property name="sessionDAO" ref="customSessionDao"/>
<!--设置间隔多久检查一次session的有效性 默认1分钟-->
<property name="sessionValidationInterval" value="60000"/>
<!--配置会话验证调度器-->
<!--<property name="sessionValidationScheduler" ref="sessionValidationScheduler"/>-->
<!--是否开启检测,默认开启-->
<!--<property name="sessionValidationSchedulerEnabled" value="true"/>-->
<!--是否删除无效的session,默认开启-->
<property name="deleteInvalidSessions" value="true"/>
<!--配置session监听器-->
<property name="sessionListeners">
<list>
<ref bean="shiroSessionListener"/>
</list>
</property>
<!--会话Cookie模板-->
<property name="sessionIdCookie" ref="sessionIdCookie"/>
<!--取消URL后面的JSESSIONID-->
<property name="sessionIdUrlRewritingEnabled" value="true"/>
</bean>
1.2.3 测试
我们登录以及退出查看依次打印的是哪些方法:
登录时:
退出时:
过期后:
访问方法:用户查询
结论:
当登录发送请求 会执行 监听器中的 onstart
当登出发送请求 会执行 监听器中的 onStop
当检查session过期时,会执行 监听器中的 onExpiration
过期时,需要身份验证才能访问的方法,就不会被允许访问;
二、Ehcache框架缓存管理
2.1 关于缓存管理
例如Leaf的上篇文章写的那样的Shiro授权,它的性能是非常差的:
每一次访问新的功能或者单纯访问一个页面都会重新调用一次授权的方法,
也就是会走两次数据库,性能极大的不好;
而关于Ehcache的缓存管理就是用来解决这方面问题的!
2.2 Ehcache缓存管理原理
所以我们Shiro在每次调用了用户角色权限方法后,
就把用户角色权限信息存到缓冲(内存)Ehcache中;
后面再需要访问是否拥有用户角色权限时就可以直接查询缓冲Ehcache,
如果缓冲中没有信息,才去查询数据库,并且把信息存储到Ehcache里;
这样就极大的提高了性能。
放上理解图:
2.3 初始缓存
EhcacheDemo1
package com.leaf.ssm.shiro;
import java.util.HashMap;
import java.util.Map;
/**
* @author Leaf
* @site 2977819715
* @company 玉渊工作室
* @create 2022-08-29 11:23
*/
public class EhcacheDemo1 {
static Map<String, Object> cache = new HashMap<String, Object>();
//看做是查询数据库
static Object getValue(String key) {
//默认从缓存中获取数据
Object value = cache.get(key);
if(value == null) {
//从数据库中做查询 userBiz.queryRole(1);
System.out.println("hello zs");
cache.put(key, new String[] {"zs"});
return cache.get(key);
}
return value;
}
public static void main(String[] args) {
System.out.println(getValue("sname"));
System.out.println(getValue("sname"));
}
}
运行测试:除了第一次是查询了数据库,后面一次就是直接查询的缓存内容;
上面这个就是利用Map做的缓存,主要是体验一下缓存的特点,有着很多的缺陷;
1、不能控制缓存时间;
2、Map集合中不能针对不同数据设置不同的缓存时间。
因此就需要引入一个很强大的缓存框架:Ehcache
2.4 Ehcache的使用
2.4.1 导入pom依赖
jar包版本管理:
<!-- Ehcache缓存 -->
<ehcache.version>2.10.0</ehcache.version>
<slf4j-api.version>1.7.7</slf4j-api.version>
jar包依赖:
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>${ehcache.version}</version>
</dependency>
<!-- slf4j核心包 -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j-api.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>${slf4j-api.version}</version>
<scope>runtime</scope>
</dependency>
<!--用于与slf4j保持桥接 -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
<version>${log4j2.version}</version>
</dependency>
2.4.2 导入ehcache.xml文件
ehcache.xml
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
updateCheck="false">
<!--磁盘存储:将缓存中暂时不使用的对象,转移到硬盘,类似于Windows系统的虚拟内存-->
<!--path:指定在硬盘上存储对象的路径-->
<!--java.io.tmpdir 是默认的临时文件路径。 可以通过如下方式打印出具体的文件路径 System.out.println(System.getProperty("java.io.tmpdir"));-->
<diskStore path="D://xxx"/>
<!--defaultCache:默认的管理策略-->
<!--eternal:设定缓存的elements是否永远不过期。如果为true,则缓存的数据始终有效,如果为false那么还要根据timeToIdleSeconds,timeToLiveSeconds判断-->
<!--maxElementsInMemory:在内存中缓存的element的最大数目-->
<!--overflowToDisk:如果内存中数据超过内存限制,是否要缓存到磁盘上-->
<!--diskPersistent:是否在磁盘上持久化。指重启jvm后,数据是否有效。默认为false-->
<!--timeToIdleSeconds:对象空闲时间(单位:秒),指对象在多长时间没有被访问就会失效。只对eternal为false的有效。默认值0,表示一直可以访问-->
<!--timeToLiveSeconds:对象存活时间(单位:秒),指对象从创建到失效所需要的时间。只对eternal为false的有效。默认值0,表示一直可以访问-->
<!--memoryStoreEvictionPolicy:缓存的3 种清空策略-->
<!--FIFO:first in first out (先进先出)-->
<!--LFU:Less Frequently Used (最少使用).意思是一直以来最少被使用的。缓存的元素有一个hit 属性,hit 值最小的将会被清出缓存-->
<!--LRU:Least Recently Used(最近最少使用). (ehcache 默认值).缓存的元素有一个时间戳,当缓存容量满了,而又需要腾出地方来缓存新的元素的时候,那么现有缓存元素中时间戳离当前时间最远的元素将被清出缓存-->
<defaultCache eternal="false" maxElementsInMemory="1000" overflowToDisk="false" diskPersistent="false"
timeToIdleSeconds="0" timeToLiveSeconds="600" memoryStoreEvictionPolicy="LRU"/>
<!--name: Cache的名称,必须是唯一的(ehcache会把这个cache放到HashMap里)-->
<cache name="com.leaf.one.entity.User" eternal="false" maxElementsInMemory="0"
overflowToDisk="true" diskPersistent="true" timeToIdleSeconds="0"
timeToLiveSeconds="300" memoryStoreEvictionPolicy="LRU"/>
</ehcache>
关于ehcache配置文件:
核心api对象:
cacheManager:缓存管理器
Cache :缓存对象
Element:缓存的元素
缓存策略:
1、基于内存,即服务停止,缓存数据丢失
2、基于文件存储
2.4.3 导入EhcacheUtil类
EhcacheUtil
package com.leaf.ssm.shiro;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import java.io.InputStream;
public class EhcacheUtil {
private static CacheManager cacheManager;
static {
try {
InputStream is = EhcacheUtil.class.getResourceAsStream("/ehcache.xml");
cacheManager = CacheManager.create(is);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private EhcacheUtil() {
}
//将缓存数据value 以 key 方式 放入cache中
public static void put(String cacheName, Object key, Object value) {
Cache cache = cacheManager.getCache(cacheName);
if (null == cache) {
//以默认配置添加一个名叫cacheName的Cache
cacheManager.addCache(cacheName);
cache = cacheManager.getCache(cacheName);
}
cache.put(new Element(key, value));
}
public static Object get(String cacheName, Object key) {
Cache cache = cacheManager.getCache(cacheName);
if (null == cache) {
//以默认配置添加一个名叫cacheName的Cache
cacheManager.addCache(cacheName);
cache = cacheManager.getCache(cacheName);
}
Element element = cache.get(key);
return null == element ? null : element.getValue();
}
public static void remove(String cacheName, Object key) {
Cache cache = cacheManager.getCache(cacheName);
cache.remove(key);
}
}
2.4.4 导入测试类进行测试
EhcacheDemo2
package com.leaf.ssm.shiro;
/**
* 演示利用缓存存储数据
* @author Administrator
*
*/
public class EhcacheDemo2 {
public static void main(String[] args) {
System.out.println(System.getProperty("java.io.tmpdir"));
/* 读ehcache默认配置 */
// EhcacheUtil.put("com.leaf.four.entity.Book", 11, "zhangsan");
// System.out.println(EhcacheUtil.get("com.leaf.four.entity.Book", 11));
/* 指定硬盘位置 */
EhcacheUtil.put("com.leaf.one.entity.User", 11, "zhangsan");
System.out.println(EhcacheUtil.get("com.leaf.one.entity.User", 11));
}
}
测试:
我们测试读一个没有配置的缓存条,看看是否会生成到默认的文件夹;
然后我们再测试读我们配置好的缓存条,看看会不会生成到我们指定的硬盘位置;
文件夹里也生成了数据:
结论:
这个案例测试就是说明如果没有定义的缓存条就会执行到默认的缓存条,而指定了缓存生成的硬盘位置的话就会生成到指定的位置。
2.5 授权使用缓存
通过前面两个简单案例的测试,我们已经对缓存有了一些小了解,接下来就一起正式敲敲如何在授权的方法中使用,从而解决性能差的问题。
2.5.1 编写MyRealm的授权方法
MyRealm
package com.leaf.ssm.shiro;
import com.leaf.ssm.biz.UserBiz;
import com.leaf.ssm.model.User;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.stereotype.Service;
import java.util.Set;
/**
* @author Leaf
* @site 2977819715
* @company 玉渊工作室
* @create 2022-08-26 3:37
*/
public class MyRealm extends AuthorizingRealm {
public UserBiz userBiz;
public UserBiz getUserBiz() {
return userBiz;
}
public void setUserBiz(UserBiz userBiz) {
this.userBiz = userBiz;
}
/**
* 授权
* @param principals
* @return
* 替代了昨天的shiro-web.ini
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
//拿到账户名
String userName = principals.getPrimaryPrincipal().toString();
//先从缓存中取,缓存中没有,再查询数据库,查询出数据就放入缓存
String cacheName1 = "user:role:"+userName;
String cacheName2 = "user:per:"+userName;
//从缓存中获取角色
Set<String> roleIds = (Set<String>) EhcacheUtil.get(cacheName1, userName);
//从缓存中获取权限
Set<String> perIds = (Set<String>) EhcacheUtil.get(cacheName2, userName);
//判断缓存中是否有信息
if(roleIds == null || roleIds.size() == 0){
//调用查询用户角色的方法
roleIds = userBiz.selectRoleIdsByUserName(userName);
System.out.println("从数据库中读取用户角色...");
//放到缓存中
EhcacheUtil.put(cacheName1,userName,roleIds);
}
if(perIds == null || perIds.size() == 0){
//调用查询用户权限的方法
perIds = userBiz.selectPerIdsByUserName(userName);
System.out.println("从数据库中读取用户权限...");
//放到缓存中
EhcacheUtil.put(cacheName2,userName,perIds);
}
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
//将当前登录的权限交给shiro的授权器
info.setStringPermissions(perIds);
//将当前登录的角色交给shiro的授权器
info.setRoles(roleIds);
return info;
}
/**
* 认证
* @param token
* @return
* @throws AuthenticationException
* 替代了昨天的shiro.ini
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
//拿到用户名
String userName = token.getPrincipal().toString();
//根据用户名查询到用户对象
User user = userBiz.queryUserByUserName(userName);
AuthenticationInfo info = new SimpleAuthenticationInfo(
user.getUsername(),
user.getPassword(),
ByteSource.Util.bytes(user.getSalt()),
this.getName() // realm的名字
);
return info;
}
}
2.5.2 测试
登录:
打断点:
第一次登录,查询了数据库:
访问修改密码的方法:
断点直接跳过了查询数据库的代码段,使用缓存中的信息进行授权,访问方法。
OK,授权中使用缓存成功,测试完毕。