框架默认支持 EhCache 二级缓存
一、EhCache 二级缓存的作用
- 核心优势:可显著降低数据库访问频次,提升系统响应速度。二、开启二级缓存的方式
- 在目标 Mapper 类上添加 @CacheNamespace(implementation = LoggingEhcache.class) 注解,该 Mapper 下的所有方法将开启二级缓存。
- 修改 ehcache 配置参数,如果默认的够用不需要修改,就不需要添加配置。
三、二级缓存参数配置(ehcache.xml 文件)
参数默认说明:
maxElementsInMemory:默认 1000eternal:默认 falseoverflowToDisk:默认 falsediskPersistent:默认 falsetimeToIdleSeconds:默认 300(5分钟)timeToLiveSeconds:默认 300(5分钟)
如果要设置二级缓存参数,在项目 resources 下新建 ehcache.xml 文件,添加以下内容:
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">
<diskStore path="java.io.tmpdir" />
<!-- 默认缓存 -->
<defaultCache
eternal="false" 对象是否永久有效,一但设置了,timeout将不起作用。
maxElementsInMemory="10000" 缓存最大个数。
overflowToDisk="false" 当内存中对象数量达到maxElementsInMemory时,Ehcache将会对象写到磁盘中。
diskPersistent="false" 是否缓存虚拟机重启期数据 Whether the disk store persists between restarts of the Virtual Machine. The default value is false.
timeToIdleSeconds="6000" 设置对象在失效前的允许闲置时间(单位:秒)。仅当eternal=false对象不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大。
timeToLiveSeconds="6000" 设置对象在失效前允许存活时间(单位:秒)。最大时间介于创建时间和失效时间之间。仅当eternal=false对象不是永久有效时使用,默认是0.,也就是对象存活时间无穷大。
memoryStoreEvictionPolicy="LRU" />
</ehcache>四、集群模式如何使用 ehcache
- 添加
Terracotta依赖 - 配置
Terracotta服务器 - 修改
Ehcache配置 - 更新
Ehcache配置代码
补充说明
