Springboot集成Ehcache缓存(主要用在登录后做保持会话验证)

EhCache是一个比较成熟的Java缓存框架,最早从hibernate发展而来, 是进程中的缓存系统,它提供了用内存,磁盘文件存储,以及分布式存储方式等多种灵活的cache管理方案,快速简单。

Springboot对ehcache的使用非常支持,所以在Springboot中只需做些配置就可使用,且使用方式也简易。

在你的项目上配置以下几步即可使用

第一步

pom.xml加依赖;

<!-- Ehcache 坐标 -->
<dependency>
    <groupId>net.sf.ehcache</groupId>
    <artifactId>ehcache</artifactId>
</dependency>

第二步

创建ehcache.xml配置文件

位置:classpath目录下,即src/main/resources/ehcache.xml

内容:

<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">

    <!--磁盘存储路径-->
    <diskStore path="java.io.tmpdir"/>

    <!--defaultCache:echcache的默认缓存策略  -->
    <defaultCache
            maxElementsInMemory="10000"
            eternal="false"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            maxElementsOnDisk="10000000"
            diskExpiryThreadIntervalSeconds="120"
            memoryStoreEvictionPolicy="LRU">
        <persistence strategy="localTempSwap"/>
    </defaultCache>

    <!--accessToken缓存策略:自定义缓存策略-->
    <cache name="accessToken"
           maxElementsInMemory="10000"
           overflowToDisk="false"
           eternal="false"
           timeToIdleSeconds="1800"
           timeToLiveSeconds="0"
           maxElementsOnDisk="10000000"
           diskExpiryThreadIntervalSeconds="120"
           memoryStoreEvictionPolicy="LRU">
        <persistence strategy="localTempSwap"/>
    </cache>
</ehcache>

说明:

1、<diskStore path="java.io.tmpdir"/>

磁盘存储路径,当内存缓存满了的时候,就会往这里面放,java.io.tmdir是操作系统缓存的临时目录,不同操作系统缓存目录不一样。

2、maxElementsInMemory:内存缓存中最多可以存放的元素数量,若放入Cache中的元素超过这个数值,则有以下两种情况:

1)若overflowToDisk=true,则会将Cache中多出的元素放入磁盘文件中;

2)若overflowToDisk=false,则根据memoryStoreEvictionPolicy策略替换Cache中原有的元素

3、overflowToDisk:内存不足时,是否启用磁盘缓存

4、eternal 缓存中对象是否永久有效

5、timeToIdleSeconds 缓存数据在失效前的允许闲置时间(单位:秒),仅当eternal=false时使用,默认值是0表示可闲置时间无穷大,若超过这个时间没有访问此Cache中的某个元素,那么此元素将被从Cache中清除

6、timeToLiveSeconds 缓存数据的总的存活时间(单位:秒),仅当eternal=false时使用,从创建开始计时,失效结束。

7、maxElementsOnDisk 磁盘缓存中最多可以存放的元素数量,0表示无穷大

8、diskExpiryThreadIntervalSeconds 磁盘缓存的清理线程运行间隔,默认是120秒

9、memoryStoreEvictionPolicy 内存存储与释放策略,即达到maxElementsInMemory限制时,Ehcache会根据指定策略清理内存 共有三种策略,分别为LRU(最近最少使用)、LFU(最常用的)、FIFO(先进先出)

下面说说他们之间的关系:

eternal不多说,true表示缓存永久有效,false表示不为永久有效

主要是timeToLiveSeconds 和timeToIdleSeconds 之间的使用(单独配置时,以上已说明)

举例说明1:timeToLiveSeconds =3600 timeToIdleSeconds =300

以上配置代表缓存有效时间为3600秒(自缓存建立起一个小时有效 ),在有效的一个小时内,如果连续五分钟未访问缓存,则缓存失效,特别说明的是,就算缓存访问从未间断,到一个小时后,缓存也会失效

举例说明2:timeToLiveSeconds =0 timeToIdleSeconds =300

以上配置代表缓存有效时间为永远有效,如果连续五分钟未访问缓存,则缓存失效。特别说明的是,如果缓存访问从未间断,该缓存会一直有效

另外,defaultCache是默认缓存方式,cache是自定义的缓存方式,自行设置name。这里设置为accessToken

第三步

在Springboot配置文件中把ehcache.xml配置进去;即在application.properties中加入以下配置代码

spring.cache.ehcache.config=ehcache.xml

第三步结束,ehcache在Springboot中就配置完成了,下面就是怎么在Springboot中使用。

第四步

在启动类前加上@EnableCaching注解;这样的话,启动类启动时会去启动缓存启动器。

@SpringBootApplication
@EnableCaching
public class ZuulApplication {
   public static void main(String[] args) {
      SpringApplication.run(ZuulApplication.class, args);
   }
}

第五步

实现缓存方法

@Component
public class TokenCache {
    public static final String CACHE_NAME = "accessToken";

    //生成token存入缓存
    @Cacheable(value = CACHE_NAME, key = "#token")
    public String setCache(String token) {
        System.out.println("set token:将token放入缓存");
        return token;
    }

    //判断token是否存在缓存。不存在返回checkfail;存在返回token,并自动刷新闲置时间
    @Cacheable(value = CACHE_NAME, key = "#token")
    public String checkToken(String token) {
        System.out.println("check fail:token验证失败");
        return "checkfail";
    }

    //清空token缓存
    @CacheEvict(value = CACHE_NAME, allEntries=true)
    public void cleanAllToken() {
        System.out.println("clean all token:清空所有token");
    }

}

CACHE_NAME 为上面配置时的缓存规则名称,需要先声明一下

在方法setCache里面,做各种逻辑处理。缓存数据以kv形式存, 这里测试以value为key,以及value

第一次调用时候返回的值就会保存在缓存里。

这里为了更直观的体现出来,可以第一次调用setCache方法,把数据放到缓存里,第二次调用tokencheck方法,参数传上面的token值,返回的不是checkfail  而是setCache方法return的值

cleanAllToken:用于清空所有缓存。系统可以做个定时清空缓存,防止恶意访问导致的token占用

第六步

使用缓存方法

@Autowired
private TokenCache tokenCache;//缓存方法类

新建一个token缓存

tokenCache.setCache(accessToken);

token缓存验证

String token = tokenCache.checkToken(accessToken.toString());
if(token.equals("checkfail")){
    //过期:拦截并终止请求
}else{
    //token正确,自动刷新闲置时间,转发请求
}

 

参考:https://blog.csdn.net/wuerwei1/article/details/80604142

https://www.cnblogs.com/xzmiyx/p/9897623.html

转载于:https://my.oschina.net/u/2351298/blog/3005167

本工程用于研究如何借助Ehcache缓存框架实现对页面的缓存 本工程编码方式:UTF-8 本工程开发工具:MyEclipse 说明: 1、ehcache.xml和ehcache.xsd两个文件可以在下在下载下来的名为“ehcache-core-x.x.x-distribution.tar.gz”压缩文件中找到 2、由于要实现Ehcache缓存页面,所以必须要添加“ehcache-web-2.0.4.jar” jar包,该jar包主要用于辅助Ehcache实现页面缓存 注意: 本web工程的发布不要使用Tomcat7,否则会出现如下异常: 2015-3-25 9:53:50 org.apache.catalina.loader.WebappClassLoader loadClass 信息: Illegal access: this web application instance has been stopped already. Could not load net.sf.ehcache.store.disk.DiskStore$KeySet. The eventual following stack trace is caused by an error thrown for debugging purposes as well as to attempt to terminate the thread which caused the illegal access, and has no functional impact. java.lang.IllegalStateException at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1600) at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1559) at net.sf.ehcache.store.disk.DiskStore.keySet(DiskStore.java:560) at net.sf.ehcache.store.disk.DiskStorageFactory$DiskExpiryTask.run(DiskStorageFactory.java:838) at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:441) at java.util.concurrent.FutureTask$Sync.innerRunAndReset(FutureTask.java:317) at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:150) at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$101(ScheduledThreadPoolExecutor.java:98) at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.runPeriodic(ScheduledThreadPoolExecutor.java:181) at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:205) at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908) at java.lang.Thread.run(Thread.java:619) 相关jar包下载地址: Ehcache 对象、数据缓存:http://ehcache.org/downloads/destination?name=ehcache-core-2.5.2-distribution.tar.gz&bucket=tcdistributions&file=ehcache
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值