Shiro整合EhCache

编程入门 行业动态 更新时间:2024-10-26 08:25:05

<a href=https://www.elefans.com/category/jswz/34/1769573.html style=Shiro整合EhCache"/>

Shiro整合EhCache

缓存工具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"/><!--默认缓存--><defaultCachemaxEntriesLocalHeap="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 storepersists between restarts of the Virtual Machine. The default valueis 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"/><!--默认缓存--><defaultCachemaxEntriesLocalHeap="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.demoponent.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 {@Autowiredprivate MyRealm myRealm;//配置 SecurityManager@Beanpublic DefaultWebSecurityManager defaultWebSecurityManager(){//1 创建 defaultWebSecurityManager 对象DefaultWebSecurityManager defaultWebSecurityManager = newDefaultWebSecurityManager();//2 创建加密对象,并设置相关属性HashedCredentialsMatcher matcher = newHashedCredentialsMatcher();//2.1 采用 md5 加密matcher.setHashAlgorithmName("md5");//2.2 迭代加密次数matcher.setHashIterations(3);//3 将加密对象存储到 myRealm 中myRealm.setCredentialsMatcher(matcher);//4 将 myRealm 存入 defaultWebSecurityManager 对象defaultWebSecurityManager.setRealm(myRealm);//4.5 设置 rememberMedefaultWebSecurityManager.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 = newCookieRememberMeManager();cookieRememberMeManager.setCookie(rememberMeCookie());cookieRememberMeManager.setCipherKey("1234567890987654".getBytes());return cookieRememberMeManager;}@Beanpublic static DefaultAdvisorAutoProxyCreator getDefaultAdvisorAutoProxyCreator(){DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator=new DefaultAdvisorAutoProxyCreator();defaultAdvisorAutoProxyCreator.setUsePrefix(true);return defaultAdvisorAutoProxyCreator;}//配置 Shiro 内置过滤器拦截范围@Beanpublic 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;}@Beanpublic ShiroDialect shiroDialect(){return new ShiroDialect();}
}

测试

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

 

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

更多推荐

Shiro整合EhCache

本文发布于:2023-12-03 06:55:16,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1652376.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Shiro   EhCache

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!