SpringBoot的缓存机制
SpringBoot 3.1中开始对缓存提供支持,核心思想是对方法的缓存,当开发者调用一个方法是,将方法的数和返回值作为Key/Value形式缓存起来。再次调用该方法时,如果缓存中有数据,就从缓存中直接拿取数据,否则再去执行该方法,但是,SpringBoot并未提供缓存的实现,而是提供一套缓存的API,使开发者可以自由的选择选择缓存的实现方法,SpringBoot支持的缓存有一下几种:
JCache(JSP-107)
EhCahe 2.x
Hazelcast
Infinispan
Couchbase
Redis
Caffeine
Simple
本章我们将介绍EhCahe 2.x 和 Redis,由于Spring早已将缓存领域统一,因此无论使用哪种缓存实现,不同的只是缓存配置,一般使用的缓存注解都是一致的(Spring的缓存注解和各种缓存实现的关系就像JDBC和各种数据库驱动的关系一样)
EhCahe 2.x
EhCahe 2.x 缓存在java开发领域早已久负盛名,在SpringBoot中,值需要一个配置文件就可以将EhCahe集成到项目中,EhCahe 2.x 操作步骤如下:
1. 创建项目添加缓存依赖
创建SpringBoot项目,添加spring-boot-starter-cache 依赖以及EhCahe 依赖,
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
2. 添加缓存配置文件
如果EhCahe的缓存存在,并且classpath下有一个名为ehcache.xml的EhCahe文件,那么EhCacheCacheManager将会自动作为缓存的实现,因此,在resources目录下创建ehcache.xml文件作为EhCahe缓存的配置文件,代码如下:
<eacache>
<diskStore path="java.io.temdir/cache"/>
<defaultCache maxElemensInMemory=