一直也没有更新过新的内容,今天记录一下SpringBoot集成Ehcache缓存。
直接上内容。
步骤如下:
第一步:
创建springboot工程时加入cache依赖:
在pom.xml 文件里加入:
<!-- EhCache缓存 -->
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>2.10.4</version>
</dependency>
第二步:
application.yml 缓存配置 ,我习惯用 .yml 格式,比较简洁
在 src/mian/resources 下创建 config 文件夹存放,可以是别的,路径自定。
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">
<cache name="xn" eternal="false" maxElementsInMemory="5000"
timeToIdleSeconds="1800" />
<!-- name:缓存名称。
maxElementsInMemory:缓存最大数目
maxElementsOnDisk:硬盘最大缓存个数。
eternal:对象是否永久有效,一但设置了,timeout将不起作用。
timeToIdleSeconds:设置对象在失效前的允许闲置时间(单位:秒)。
仅当eternal=false对象不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大。 -->
启动类中加入 @EnableCaching 注解, 启用Spring的注释驱动的缓存管理功能
最后一步:
在业务实现层加入注解:
@Cacheable (cacheNames = "xn")
如:
cacheNames中的值 xn 代表缓存中的名称
第一次查询,从数据库中获取内容
第二次查询直接从缓存中获取内容,至此,springboot 集成ehcache 缓存完成