【Springboot】Springboot整合Ehcache

刚刚项目上线了,记录下使用的技术......

EhCache 是一个纯Java的进程内缓存框架,具有快速、精干等特点,是Hibernate中默认的CacheProvider。

Ehcache的特点

(1)快速简单,具有多种缓存策略

(2)缓存数据有两级为内存和磁盘,缓存数据会在虚拟机重启的过程中写入磁盘

(3)可以通过RMI、可插入API等方式进行分布式缓存

(4)具有缓存和缓存管理器的侦听接口

(5)支持多缓存管理器实例,以及一个实例的多个缓存区域。并提供Hibernate的缓存实现

项目涉及到的是报文协议转换,使用到各类api或报文格式模版需要缓存至内存中以减少报文转换耗时,选择Ehcache也是比较适合的,快速、简单

话不多说,搭个小demo

一、Springboot整合Ehcache

  1. 配置依赖

    pom.xml中添加ehcache依赖   

  <dependency>

        <groupId>net.sf.ehcache</groupId>

        <artifactId>ehcache</artifactId>

  </dependency>

 

  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:指定在硬盘上存储对象的路径

        path可以配置的目录有:

            user.home(用户的家目录)

            user.dir(用户当前的工作目录)

            java.io.tmpdir(默认的临时目录)

            ehcache.disk.store.dir(ehcache的配置目录)

            绝对路径(如:d:\\ehcache)

        查看路径方法:String tmpDir = System.getProperty("java.io.tmpdir");

     -->

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

<!--

        eternal:缓存内容是否永久存储在内存;该值设置为true时,timeToIdleSeconds和timeToLiveSeconds两个属性的值就不起作用了

        maxElementsInMemory:设置了缓存的上限,最多存储多少个记录对象

        timeToIdleSeconds:缓存创建以后,最后一次访问缓存的日期至失效之时的时间间隔;默认值是0,也就是可闲置时间无穷大

        timeToLiveSeconds:缓存自创建日期起至失效时的间隔时间;默认是0.也就是对象存活时间无穷大

        overflowToDisk:如果内存中的数据超过maxElementsInMemory,是否使用磁盘存储

        diskPersistent:磁盘存储的条目是否永久保存

        maxElementsOnDisk:硬盘最大缓存个数

        memoryStoreEvictionPolicy:默认策略是 LRU(最近最少使用)。你可以设置为FIFO(先进先出)或是LFU(较少使用)

     

     -->

 

<cache name="usercache" eternal="false" maxElementsInMemory="10000"

overflowToDisk="true" diskPersistent="false" maxElementsOnDisk="0" timeToIdleSeconds="0" timeToLiveSeconds="0"

memoryStoreEvictionPolicy="LRU" />

</ehcache>

3.配置启用ehcache注解

1 @SpringBootApplication
2 @EnableCaching
3 public class App {
4     public static void main(String[] args) {
5         SpringApplication.run(App.class, args);
6     }
7 }

4.

 

 

 

 

猜你喜欢

转载自www.cnblogs.com/Y-S-X/p/11391834.html