shiro04 (会话与缓存)

发布于:2023-01-04 ⋅ 阅读:(211) ⋅ 点赞:(0)

目录

一,会话

二,缓存


一,会话

Shiro提供了完整的企业级会话管理功能,不依赖于底层容器(如Tomcat),不管是J2SE还是J2EE环境都可以使用,提供了会话管理,会话事件监听,会话存储/持久化,容器无关的集群,失效/过期支持,对Web的透明支持,SSO单点登录的支持等特性。
  
  所谓会话,即用户访问应用时保持的连接关系,在多次交互中应用能够识别出当前访问的用户是谁,且可以在多次交互中保存一些数据。如访问一些网站时登录成功后,网站可以记住用户,且在退出之前都可以识别当前用户是谁。

会话监听器:

package com.ruojuan.ssm.shiro;

import org.apache.shiro.session.Session;
import org.apache.shiro.session.SessionListener;

/**
 * @author ruojuan
 * @site 123456999
 * @company 玉渊工作室
 * @create 2022-08-27 11:21
 */
public class MysessionListener 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());
    }
}

apllicationContext-shiro.xml

 <!--会话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

过期时,需要身份验证才能访问的方法,就不会被允许访问;

二,缓存

1.为什么要使用缓存

  在没有使用缓存的情况下,我们每次发送请求都会调用一次doGetAuthorizationInfo方法来进行用户的授权操作,但是我们知道,一个用户具有的权限一般不会频繁的修改,也就是每次授权的内容都是一样的,所以我们希望在用户登录成功的第一次授权成功后将用户的权限保存在缓存中,下一次请求授权的话就直接从缓存中获取,这样效率会更高一些。
  
  2.什么是ehcache

  Ehcache是现在最流行的纯Java开源缓存框架,配置简单、结构清晰、功能强大。是Hibernate中默认CacheProvider。Ehcache是一种广泛使用的开源Java分布式缓存。主要面向通用缓存,Java EE和轻量级容器。它具有内存和磁盘存储,缓存加载器,缓存扩展,缓存异常处理程序,一个gzip缓存servlet过滤器,支持REST和SOAP api等特点。

3.ehcache特点
  
  1) 够快
      Ehcache的发行有一段时长了,经过几年的努力和不计其数的性能测试,Ehcache终被设计于large, high concurrency systems.
  2) 够简单
      开发者提供的接口非常简单明了,从Ehcache的搭建到运用运行仅仅需要的是你宝贵的几分钟。其实很多开发者都不知道自己用在用Ehcache,Ehcache被广泛的运用于其他的开源项目
  3) 够袖珍
      关于这点的特性,官方给了一个很可爱的名字small foot print ,一般Ehcache的发布版本不会到2M,V 2.2.3 才 668KB。
  4) 够轻量
      核心程序仅仅依赖slf4j这一个包,没有之一!
  5) 好扩展
      Ehcache提供了对大数据的内存和硬盘的存储,最近版本允许多实例、保存对象高灵活性、提供LRU、LFU、FIFO淘汰算法,基础属性支持热配置、支持的插件多
  6) 监听器
      缓存管理器监听器 (CacheManagerListener)和 缓存监听器(CacheEvenListener),做一些统计或数据一致性广播挺好用的
  7) 分布式缓存
      从Ehcache 1.2开始,支持高性能的分布式缓存,兼具灵活性和扩展性

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="60" timeToLiveSeconds="600" memoryStoreEvictionPolicy="LRU"/>


    <!--name: Cache的名称,必须是唯一的(ehcache会把这个cache放到HashMap里)-->
    <cache name="com.ruojuan.one.entity.User" eternal="false" maxElementsInMemory="100"
           overflowToDisk="true" diskPersistent="true" timeToIdleSeconds="0"
           timeToLiveSeconds="300" memoryStoreEvictionPolicy="LRU"/>
</ehcache>

EhcaheUtils.java

package com.ruojuan.ssm.util;

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);
    }
}

MyRealm.java

package com.ruojuan.ssm.shiro;

import com.ruojuan.ssm.biz.UserBiz;
import com.ruojuan.ssm.model.User;
import com.ruojuan.ssm.util.EhcacheUtil;
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 java.util.Set;

/**
 * @author ruojuan
 * @site 123456999
 * @company 玉渊工作室
 * @create 2022-08-25 11:34
 */
public class MyRealm extends AuthorizingRealm{

    private UserBiz userBiz;

    public UserBiz getUserBiz() {
        return userBiz;
    }

    public void setUserBiz(UserBiz userBiz) {
        this.userBiz = userBiz;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("用户授权。。。");
        String username = principals.getPrimaryPrincipal().toString();
        //先从缓存中  缓存中没有,在查询数据库 查询出数据放入缓存
        String cacheName1 = "user:role:"+username;
        String cacheName2 = "user:per:"+username;
        //转成字符形式
        //用户
        //User user = userBiz.queryByName(username);
        //拿到角色id
        //从缓存中获取角色
        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.getRolesByUserName(username);
            System.out.println("从数据库中读取用户角色。。。。");
        }

        if(perIds==null||perIds.size()==0){
            perIds = userBiz.getPersByUserName(username);
            System.out.println("从数据库中读取用户权限。。。。");
        }

        //授权
        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
        //角色
        info.setRoles(roleIds);
        //权限
        info.setStringPermissions(perIds);

        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("身份认证...");
        String username = token.getPrincipal().toString();
        //String password = token.getCredentials().toString();
        User user = userBiz.queryByName(username);
//        拿到数据库中的用户信息,放入token凭证中,用于controler进行对比
        AuthenticationInfo info = new SimpleAuthenticationInfo(
                user.getUsername(),
                user.getPassword(),
                ByteSource.Util.bytes(user.getSalt()),
                this.getName()
        );
        return info;
    }
}

本文含有隐藏内容,请 开通VIP 后查看

网站公告

今日签到

点亮在社区的每一天
去签到