https://www.cnblogs.com/wangwiz/articles/7691381.html
https://blog.csdn.net/vbirdbest/article/details/72763048
项目中一般使用到多级缓存,就是多层缓存(二级缓存的比较多),目的都是为了减轻数据库压力。查找数据时,先在一级缓存中查找,找不到去二级,以此类推……,最后再查询数据库。
一般二级缓存可以是这样的(将Ehcache(一级)与Redis(二级)配合搭建的二级缓存):
先查Ehcache,如果不存在,再查Redis,如果还不存在,再查数据库。(如果查到数据了,需要更新之前的相关缓存)
注:ehcache 是一个纯Java的进程内缓存框架,直接在jvm虚拟机中缓存数据,是Hibernate中默认的CacheProvider。缓存数据有两级:内存和磁盘,因此无需担心容量和数据安全问题。缓存数据会在虚拟机重启的过程中写入磁盘(即JVM关闭会自动调用shutdown()函数,ehcache需要flush或shutdown后才会持久化到磁盘)。不建议使用它的分布式缓存方式(缓存共享复杂,维护不方便)。
使用步骤:
一、在pom.xml中引入依赖
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>2.10.5</version>
</dependency>
二、在classpath根目录下创建一个配置文件 ehcache.xml,内容参考:
<?xml version="1.0" encoding="UTF-8"?>
<ehcache updateCheck="false" dynamicConfig="false">
<!-- 磁盘缓存位置 -->
<diskStore path="java.io.tmpdir/ehcache"/>
<!-- 默认配置 -->
<defaultCache
maxEntriesLocalHeap="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
maxEntriesLocalDisk="10000000"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU">
</defaultCache>
<!-- helloworld缓存配置 -->
<cache name="HelloWorldCache"
maxElementsInMemory="1000"
eternal="false"
timeToIdleSeconds="5"
timeToLiveSeconds="5"
overflowToDisk="false"
memoryStoreEvictionPolicy="LRU"/>
</ehcache>