前文
Spring 提供的缓存
从 Spring 3.1 开始对缓存提供了支持,核心思路是对方法的缓存,当开发者调用一个方法时,将方法的参数和返回值作为 key / value 缓存起来,当再次调用该方法时,如果缓存中有数据,就直接从缓存中读取,否则再去执行该方法。但是,Spring 中并未提供缓存的实现,而是提供了一套缓存的 API,开发者可以自由选择缓存的实现,目前 SpringBoot 支持的缓存有如下几种:
- JCache(JSR-107)
- EhCache 2.X
- Hazelcast
- Infinispan
- Couchbase
- Redis
- Caffeine
- Simple
EhCache
EhCache 缓存在 Java 开发领域已是久负盛名,在 SpringBoot 中,只需要一个配置文件就可以将 EhCache 集成到项目中
添加依赖
<dependencies>
<!-- 导入 web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 导入 SpringBoot 与 Cache 的整合包-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<!-- 导入 Ehcache -->
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
</dependency>
</dependencies>
创建缓存配置文件
如果 Ehcache 的依赖存在,并且在 classpath 下有一个名为 ehcache.xml 的 Ehcache 配置文件,那么 EhCacheCacheManager 将会自动作为缓存的实现。因此,在 resource 目录下创建 ehcache.xml 文件作为 Ehcache 缓存的配置文件,代码如下:
<ehcache>
<diskStore path="java.io.tmpdir/cache" />
<defaultCache
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="false"
diskPersistent="false"
diskExpiryThreadIntervalSeconds="120"
/>
<!-- name 表示缓存名称 -->
<!-- maxElementsInMemory 表示缓存的最大个数 -->
<!-- eternal 表示缓存对象是否永久有效,一旦设置永久有效,那么 timeout 将不起作用 -->
<!-- timeToIdleSeconds 表示缓存对象在失效前的允许闲置时间(单位:s),当 eternal 设置为 false 时该属性才生效 -->
<!-- timeToLiveSeconds 表示缓存对象在失效前允许存活的时间(单位:s),当 eternal 设置为 false 时该属性才生效 -->
<!-- overflowToDisk 表示当内存中的对象数量达到 maxElementsInMemory 时,Ehcache 是否将对象写进磁盘中 -->
<!-- diskExpiryThreadIntervalSeconds 表示磁盘失效线程运行时间间隔 -->
<cache name="user_cache"

本文详细介绍如何在SpringBoot项目中整合EhCache缓存,包括添加依赖、配置缓存、开启缓存、创建实体类、DAO及自定义缓存key生成器等步骤。
最低0.47元/天 解锁文章
3169

被折叠的 条评论
为什么被折叠?



