Shiro整合EhCache

news2024/10/6 8:30:46

缓存工具EhCache

EhCache是一种广泛使用的开源Java分布式缓存。主要面向通用缓存,Java EE和轻量级容器。可以和大部分Java项目无缝整合,例如:Hibernate中的缓存就是基于EhCache实现的。EhCache支持内存和磁盘存储,默认存储在内存中,如内存不够时把缓存数据同步到磁盘中。EhCache支持基于Filter的Cache实现,也支持Gzip压缩算法。 EhCache直接在JVM虚拟机中缓存,速度快,效率高;EhCache缺点是缓存共享麻烦,集群分布式应用使用不方便

添加依赖

<dependency>
 <groupId>net.sf.ehcache</groupId>
 <artifactId>ehcache</artifactId>
 <version>2.6.11</version>
 <type>pom</type>
</dependency>

添加配置文件 ehcache.xml

<?xml version="1.0" encoding="UTF-8"?>
<ehcache>
    <!--磁盘的缓存位置-->
    <diskStore path="java.io.tmpdir/ehcache"/>
    <!--默认缓存-->
    <defaultCache
            maxEntriesLocalHeap="10000"
            eternal="false"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            maxEntriesLocalDisk="10000000"
            diskExpiryThreadIntervalSeconds="120"
            memoryStoreEvictionPolicy="LRU">
        <persistence strategy="localTempSwap"/>
    </defaultCache>
    <!--helloworld 缓存-->
    <cache name="HelloWorldCache"
           maxElementsInMemory="1000"
           eternal="false"
           timeToIdleSeconds="5"
           timeToLiveSeconds="5"
           overflowToDisk="false"
           memoryStoreEvictionPolicy="LRU"/>
    <!--
    defaultCache:默认缓存策略,当 ehcache 找不到定义的缓存时,则使用这个
   缓存策略。只能定义一个。
    -->
    <!--
    name:缓存名称。
    maxElementsInMemory:缓存最大数目
    maxElementsOnDisk:硬盘最大缓存个数。
    eternal:对象是否永久有效,一但设置了,timeout 将不起作用。
    overflowToDisk:是否保存到磁盘,当系统宕机时
    timeToIdleSeconds:设置对象在失效前的允许闲置时间(单位:秒)。仅当
   eternal=false 对象不是永久有效时使用,可选属性,默认值是 0,也就是可闲置时间
   无穷大。
    timeToLiveSeconds:设置对象在失效前允许存活时间(单位:秒)。最大时间
   介于创建时间和失效时间之间。仅当 eternal=false 对象不是永久有效时使用,默认
   是 0.,也就是对象存活时间无穷大。
    diskPersistent:是否缓存虚拟机重启期数据 Whether the disk store
   persists between restarts of the Virtual Machine. The default value
   is false.
    diskSpoolBufferSizeMB:这个参数设置 DiskStore(磁盘缓存)的缓存区大
   小。默认是 30MB。每个 Cache 都应该有自己的一个缓冲区。
    diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是
   120 秒。
    memoryStoreEvictionPolicy:当达到 maxElementsInMemory 限制时,
   Ehcache 将会根据指定的策略去清理内存。默认策略是 LRU(最近最少使用)。你可以
   设置为 FIFO(先进先出)或是 LFU(较少使用)。
    clearOnFlush:内存数量最大时是否清除。
    memoryStoreEvictionPolicy:可选策略有:LRU(最近最少使用,默认策
   略)、FIFO(先进先出)、LFU(最少访问次数)。
    FIFO,first in first out,这个是大家最熟的,先进先出。
    LFU, Less Frequently Used,就是上面例子中使用的策略,直白一点就是
   讲一直以来最少被使用的。如上面所讲,缓存的元素有一个 hit 属性,hit 值最小的将
   会被清出缓存。
    LRU,Least Recently Used,最近最少使用的,缓存的元素有一个时间戳,当
   缓存容量满了,而又需要腾出地方来缓存新的元素的时候,那么现有缓存元素中时间戳
   离当前时间最远的元素将被清出缓存。
    -->
</ehcache>

测试

创建测试类,操作缓存
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

import java.io.InputStream;

public class TestEH {
  public static void main(String[] args) {
     //获取编译目录下的资源的流对象
     InputStream input = TestEH.class.getClassLoader().getResourceAsStream("ehcache.xml");
     //获取 EhCache 的缓存管理对象
     CacheManager cacheManager = new CacheManager(input);
     //获取缓存对象
     Cache cache = cacheManager.getCache("HelloWorldCache");
     //创建缓存数据
     Element element = new Element("name","zhang3");
     //存入缓存
     cache.put(element);
     //从缓存中取出
     Element element1 = cache.get("name");
     System.out.println(element1.getObjectValue());
  }
}

Shiro整合EhCache 

Shiro官方提供了shiro-ehcache,实现了整合EhCache作为Shiro的缓存工具。可以缓存认证执行的Realm方法,减少对数据库的访问,提高认证效率。
SpringBoot整合Shiro: SpringBoot整合Shiro-CSDN博客

添加依赖

<!--Shiro 整合 EhCache-->
<dependency>
 <groupId>org.apache.shiro</groupId>
 <artifactId>shiro-ehcache</artifactId>
 <version>1.4.2</version>
</dependency>
<dependency>
 <groupId>commons-io</groupId>
 <artifactId>commons-io</artifactId>
 <version>2.6</version>
</dependency>

添加配置文件

在 resources 下添加配置文件 ehcache/ ehcache-shiro.xml
<?xml version="1.0" encoding="UTF-8"?>
<ehcache name="ehcache" updateCheck="false">
    <!--磁盘的缓存位置-->
    <diskStore path="java.io.tmpdir"/>
    <!--默认缓存-->
    <defaultCache
            maxEntriesLocalHeap="1000"
            eternal="false"
            timeToIdleSeconds="3600"
            timeToLiveSeconds="3600"
            overflowToDisk="false">
    </defaultCache>
    <!--登录认证信息缓存:缓存用户角色权限-->
    <cache name="loginRolePsCache"
           maxEntriesLocalHeap="2000"
           eternal="false"
           timeToIdleSeconds="600"
           timeToLiveSeconds="0"
           overflowToDisk="false"
           statistics="true"/>
</ehcache>

修改配置类

修改配置类 ShiroConfig

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import com.example.demo.component.MyRealm;
import net.sf.ehcache.CacheManager;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;

import org.apache.shiro.cache.ehcache.EhCacheManager;
import org.apache.shiro.io.ResourceUtils;
import org.apache.shiro.spring.web.config.DefaultShiroFilterChainDefinition;
import org.apache.shiro.web.mgt.CookieRememberMeManager;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.servlet.SimpleCookie;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.io.InputStream;

@Configuration
public class ShiroConfig {
      @Autowired
      private MyRealm myRealm;

    //配置 SecurityManager
    @Bean
    public DefaultWebSecurityManager defaultWebSecurityManager(){
        //1 创建 defaultWebSecurityManager 对象
        DefaultWebSecurityManager defaultWebSecurityManager = new
                DefaultWebSecurityManager();
        //2 创建加密对象,并设置相关属性
        HashedCredentialsMatcher matcher = new
                HashedCredentialsMatcher();
        //2.1 采用 md5 加密
        matcher.setHashAlgorithmName("md5");
        //2.2 迭代加密次数
        matcher.setHashIterations(3);
        //3 将加密对象存储到 myRealm 中
        myRealm.setCredentialsMatcher(matcher);
        //4 将 myRealm 存入 defaultWebSecurityManager 对象
        defaultWebSecurityManager.setRealm(myRealm);
        //4.5 设置 rememberMe

        defaultWebSecurityManager.setRememberMeManager(rememberMeManager());
        //4.6 设置缓存管理器
        defaultWebSecurityManager.setCacheManager(getEhCacheManager());
        //5 返回
        return defaultWebSecurityManager;
    }
    //缓存管理器
    public EhCacheManager getEhCacheManager(){
        EhCacheManager ehCacheManager = new EhCacheManager();
        InputStream is = null;
        try {
            is = ResourceUtils.getInputStreamForPath(
                    "classpath:ehcache/ehcache-shiro.xml");
        } catch (IOException e) {
            e.printStackTrace();
        }
        CacheManager cacheManager = new CacheManager(is);
        ehCacheManager.setCacheManager(cacheManager);
        return ehCacheManager;
    }
    //cookie 属性设置
    public SimpleCookie rememberMeCookie(){
        SimpleCookie cookie = new SimpleCookie("rememberMe");
        //设置跨域
        //cookie.setDomain(domain);
        cookie.setPath("/");
        cookie.setHttpOnly(true);
        cookie.setMaxAge(30*24*60*60);
        return cookie;
    }
    //创建 Shiro 的 cookie 管理对象
    public CookieRememberMeManager rememberMeManager(){
        CookieRememberMeManager cookieRememberMeManager = new
                CookieRememberMeManager();
        cookieRememberMeManager.setCookie(rememberMeCookie());

        cookieRememberMeManager.setCipherKey("1234567890987654".getBytes());
        return cookieRememberMeManager;
    }

    @Bean
    public static DefaultAdvisorAutoProxyCreator getDefaultAdvisorAutoProxyCreator(){

        DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator=new DefaultAdvisorAutoProxyCreator();
        defaultAdvisorAutoProxyCreator.setUsePrefix(true);

        return defaultAdvisorAutoProxyCreator;
    }
    //配置 Shiro 内置过滤器拦截范围
    @Bean
    public DefaultShiroFilterChainDefinition shiroFilterChainDefinition(){

        DefaultShiroFilterChainDefinition definition = new DefaultShiroFilterChainDefinition();
        //设置不认证可以访问的资源
        definition.addPathDefinition("/myController/userLogin", "anon");
        definition.addPathDefinition("/myController/login","anon");
        //配置登出过滤器
        definition.addPathDefinition("/logout","logout");
        //设置需要进行登录认证的拦截范围
        definition.addPathDefinition("/**","authc");

        //添加存在用户的过滤器(rememberMe)
        definition.addPathDefinition("/**","user");
        return definition;
    }
    @Bean
    public ShiroDialect shiroDialect(){
        return new ShiroDialect();
    }
}

测试

第一次登录可以看到查询角色、权限信息

 

先清除日志,再点击角色认证、权限认证,查看日志,没有查询数据库。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1139204.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

netcore webapi action 同时支持 get 和 post 请求

最近在项目开发过程中&#xff0c;有个别接口需要同时支持GET和POST请求&#xff0c;经过一番测试&#xff0c;貌似NetCore只能接收指定的FromBody、FromQuery等参数&#xff0c;经过一番查找后发现文章&#xff1a;为ASP.NET Core实现一个自适应ModelBinder&#xff0c;让Acti…

HackTheBox-Starting Point--Tier 1---Sequel

文章目录 一 题目二 实验过程 一 题目 Tags Vulnerability Assessment、Databases、MySQL、SQL、Reconnaissance、Weak Credentials译文&#xff1a;漏洞评估、数据库、MYSQL、SQL、侦察、凭证薄弱Connect To attack the target machine, you must be on the same network.C…

QT 中 Graphics View 程序例子-Diagram Scene Example

一、 概况 本例演示如何使用图形视图框架。 “图表场景”示例是一个应用程序&#xff0c;您可以在其中创建流程图。可以添加流程图形状和文本&#xff0c;并通过箭头连接形状&#xff0c;如上图所示。形状、箭头和文本可以赋予不同的颜色&#xff0c;并且可以更改文本的字体、…

HackTheBox-Starting Point--Tier 1---Crocodile

文章目录 一 题目二 实验过程 一 题目 Tags Web、Network、Custom Applications、Protocols、Apache、FTP、Reconnaissance、Web Site Structure Discovery、Clear Text Credentials、Anonymous/Guest Access译文&#xff1a;Web、网络、定制应用程序、协议、Apache、FTP、侦…

C++项目——云备份-③-实用工具类设计与实现

文章目录 专栏导读1.文件实用工具类的设计2.文件实用工具类的实现2.1前置知识补充2.1.1struct stat 与 stat介绍2.1.2std::experimental::filesystem认识 2.2FileUtil实现 3.JSON实用工具类的设计4.JSON实用工具类的实现5.实用工具类整理 专栏导读 &#x1f338;作者简介&#…

ESP32智能小车+PS2无线遥控器+麦克纳姆轮+microPython

from machine import Pin,PWM from ps2 import PS2Controller import time import os# ############################################# # PS2 遥控器 # ############################################# ps2ctl PS2Controller(di_pin_no26, do_pin_no27, cs_pin_no14, clk_pin…

Unity中Shader的模型网格阴影

文章目录 前言一、网格阴影原理1、在世界空间下&#xff0c;把角色模型在Y轴上压缩成一个面片&#xff0c;把颜色修改成像影子的颜色2、把压缩后的面片&#xff0c;移动到合适的位置&#xff0c;把模型和阴影面片错开3、实现距离脚近的阴影偏移少&#xff0c;距离脚远的阴影偏移…

【已解决】AttributeError: module ‘cv2‘ has no attribute ‘bgsegm‘

问题 使用cv2.bgsegm.createBackgroundSubtractorMOG()去除背景的时候&#xff0c;遇到如下问题&#xff1a; AttributeError: module cv2 has no attribute bgsegm原因 报错原因&#xff1a;使用的python环境中没有安装扩展包contrib 解决方法 可以通过pip或者conda安装 …

QT中文乱码解决方案与乱码的原因

相信大家应该都遇到过中文乱码的问题&#xff0c;有时候改一改中文就不乱码了&#xff0c;但是有时候用同样的方式还是乱码&#xff0c;那么这个乱码到底是什么原因&#xff0c;又该如何彻底解决呢&#xff1f; 总结 先总结一下&#xff1a; Qt5中&#xff0c;将QString()的构…

Java实现Csv文件导入导出

Java实现Csv文件导入导出 什么是.csv文件&#xff1f; CSV&#xff08;Comma-Separated Values&#xff0c;逗号分隔的值&#xff09;是一种简单、实用的文件格式&#xff0c;用于存储和表示包括文本、数值等各种类型的数据。CSV 文件通常以 .csv 作为文件扩展名。这种文件格…

基于蜣螂优化算法DBO优化的VMD-KELM光伏发电短期功率预测MATLAB代码

微❤关注“电气仔推送”获得资料&#xff08;专享优惠&#xff09; VMD适用于处理非线性和非平稳信号&#xff0c;例如振动信号、生物信号、地震信号、图像信号等。它在信号处理、振动分析、图像处理等领域有广泛的应用&#xff0c;特别是在提取信号中的隐含信息和去除噪声方面…

字符串中的strcpy和strncpy区别

strcpy:函数原型是char *strcpy(char* dest, const char *src)&#xff0c;含义是将src中的字符串复制到dest中。 strncpy:函数原型是char *strncpy(char *dest const char *src,int n&#xff09;&#xff0c;表示把src所指向的字符串中以src地址开始的前n个字节复制到dest所…

香港施政报告人才引进政策2023全面解读,对优才计划申请是否有影响?

香港施政报告人才引进政策2023全面解读&#xff0c;对优才计划申请是否有影响&#xff1f; 香港第二份施政报告10月25日出来了&#xff01;这次真的是“走进民生”啊&#xff0c;什么路都帮你想好了&#xff01; 总结就是&#xff1a;继续抢人才、留人才&#xff01;在昨天的《…

103.linux5.15.198 编译 firefly-rk3399(2)

1. 平台&#xff1a; rk3399 firefly 2g16g 2. 内核&#xff1a;linux5.15.136 &#xff08;从内核镜像网站下载&#xff09; 3. 交叉编译工具 gcc version 7.5.0 (Ubuntu/Linaro 7.5.0-3ubuntu1~18.04) 4. 宿主机&#xff1a;ubuntu18.04 5. 需要的素材和资料&#xff…

MySQL 单表查询 多表设计

目录 数据库操作-DQL(单表查询)语法基本查询&#xff08;不带任何条件&#xff09;条件查询&#xff08;where&#xff09;聚合函数分组查询&#xff08;group by [having]&#xff09;&#xff08;重点&#xff09;排序查询&#xff08;order by&#xff09;&#xff08;重点&…

MySQL数据库基本操作2

文章目录 主要内容一.DQL1.语法格式代码如下&#xff08;示例&#xff09;: 2.数据准备代码如下&#xff08;示例&#xff09;: 3.简单查询代码如下&#xff08;示例&#xff09;: 4.运算符5.运算符操作-算术运算符代码如下&#xff08;示例&#xff09;: 6.运算符操作-条件查询…

Spring Cloud Sentinel整合Nacos实现配置持久化

sentinel配置相关配置后无法持久化&#xff0c;服务重启之后就没了&#xff0c;所以整合nacos&#xff0c;在nacos服务持久化&#xff0c;sentinel实时与nacos通信获取相关配置。 使用上一章节Feign消费者服务实现整合。 版本信息&#xff1a; nacos:1.4.1 Sentinel 控制台 …

【DRAM存储器十七】DDR2介绍-DDR2的新增技术-Post CAS、ODT、RDQS、OCD

&#x1f449;个人主页&#xff1a;highman110 &#x1f449;作者简介&#xff1a;一名硬件工程师&#xff0c;持续学习&#xff0c;不断记录&#xff0c;保持思考&#xff0c;输出干货内容 参考资料&#xff1a;《镁光DDR数据手册》 目录 Post CAS ODT RDQS OCD Post CA…

方舟生存进化ARK个人服务器搭建教程保姆级

方舟生存进化ARK个人服务器搭建教程保姆级 大家好我是艾西&#xff0c;在很久之前我有给大家分享过方舟生存进化的搭建架设教程&#xff0c;但时间久远且以前的教程我现在回头看去在某些地方说的并不是那么清楚。最近也是闲暇无事打算重新巩固下方舟生存进化的搭建架设教程&…

[计算机提升] Windows文件系统类型介绍

1.13 文件系统 在Windows系统中&#xff0c;文件系统是一种用于组织和管理计算机上存储的文件和目录的方法。它提供了一种结构化的方式来访问、存储和检索数据。 以下是Windows系统中常见的文件系统&#xff1a; FAT&#xff08;FAT16、FAT32&#xff09;&#xff1a;FAT&…