目录
一、会话管理
运用背景:
Shiro独立的会话管理,包含了单点登录的业务场景;Nginx负载多个tomcat;
设置会话监听器
package com.zking.ssm.shiro;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.SessionListener;
/**
* @author 锦鲤
* @company 卓京公司
* @create 2022-08-28 21:21
*/
public class ShiroSessionListener implements SessionListener {
@Override
public void onStart(Session session) {
System.out.println("ShiroSessionListener.onstart..."+session.getId());
}
@Override
public void onStop(Session session) {
System.out.println("ShiroSessionListener.onStop..."+session.getId());
}
@Override
public void onExpiration(Session session) {
System.out.println("ShiroSessionListener.onExpiration..."+session.getId());
}
}
2.配置文件配置
Spring-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.zking.ssm.shiro.ShiroSessionListener"/>
<!--会话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-->
<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="false"/>
</bean>
开始测试
当登录发送请求 会执行 监听器中的 onstart
当登出发送请求 会执行 监听器中的 onStop
当检查session过期时,会执行 监听器中的 onExpiration
过期时,需要身份验证才能访问的方法,就不会被允许访问;
二、缓存管理
运用:解决反复授权查询数据库的问题
package com.zking.ssm.ehcache;
import java.util.HashMap;
import java.util.Map;
/**
* 利用map集合简易实现缓存原理
* @author锦鲤
*
*/
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) {
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"));
}
}
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.javaxl.one.entity.User" eternal="false" maxElementsInMemory="100"
overflowToDisk="true" diskPersistent="true" timeToIdleSeconds="0"
timeToLiveSeconds="300" memoryStoreEvictionPolicy="LRU"/>
</ehcache>
Ehcache的初步使用
EhcacheUtil.java
package com.zking.ssm.ehcache;
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() {
}
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);
}
}
开始测试
package com.zking.ssm.ehcache;
/**
* 演示利用缓存存储数据
* @author 锦鲤
*
*/
public class EhcacheDemo2 {
public static void main(String[] args) {
System.out.println(System.getProperty("java.io.tmpdir"));
// EhcacheUtil.put("com.javaxl.four.entity.Book", 11, "zhangsan");
// System.out.println(EhcacheUtil.get("com.javaxl.four.entity.Book", 11));
EhcacheUtil.put("com.javaxl.one.entity.User", 11, "zhangsan");
System.out.println(EhcacheUtil.get("com.javaxl.one.entity.User", 11));
}
}
Ehcache完成realm授权
Myrealm代码更新
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
String username = principals.getPrimaryPrincipal().toString();
User user = shiroUserService.queryByName(username);
String user_role_key = "user:roles:";
String user_pers_key = "user:pers:";
Set<String> roles = (Set<String>) EhcacheUtil.get(user_role_key + user.getUserid(), user.getUserid());
Set<String> pers = (Set<String>) EhcacheUtil.get(user_pers_key + user.getUserid(), user.getUserid());
if (roles == null || roles.size() == 0){
System.out.println("从数据库中获取相关角色信息...");
roles = shiroUserService.getRolesByUserId(user.getUserid());
EhcacheUtil.put(user_role_key+user.getUserid(), user.getUserid(), roles);
}
if (pers == null || pers.size() == 0){
System.out.println("从数据库中获取相关权限信息...");
pers = shiroUserService.getPersByUserId(user.getUserid());
EhcacheUtil.put(user_pers_key+user.getUserid(), user.getUserid(), pers);
}
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
info.setRoles(roles);
info.setStringPermissions(pers);
return info;
}
总结:测试会发现,只有第一次执行授权方法的时候,才会从数据库中获取用户信息,其他时候都是从缓存中拿数据;