springboot系列:使用缓存
前言:springboot已经为我们实现了抽象的api接口,因此当我们使用不同的缓存时,只是配置有可能有点区别(比如ehcache和Redis),但是在程序中使用缓存的方法是一样的。
1.springboot使用ehcache缓存
1.步骤:
1.在pom.xml中配置2个依赖,添加spring-boot-starter-cache启动器,以及ehcache。
<!-- ehcache -->
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>2.10.4</version>
</dependency>
<!-- 缓存支持启动器 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
2.在resources目录下创建ehcache.xml配置文件。
ehcache.xml配置文件格式如下(该配置文件没有文档约束):
<ehcache>
<diskStore path="java.io.tmpdir"/>
<defaultCache
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="true"
/>
<cache name="sampleCache1"
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="300"
timeToLiveSeconds="600"
overflowToDisk="true"
/>
<ehcache>
3.在application.properties文件中指定ehcache的配置文件ehcache.xml,设置spring.cache.ehcache.config=ehcache.xml。
spring.cache.ehcache.config=ehcache.xml
4.在主类上添加自动配置并启动缓存的注解@EnableCaching。
5.在类上配置缓存策略(通常在service层)。
@CacheConfig:配置用于指定ehcache.xml文件配置的缓存策略;该注解用在类上。
@Cacheable:存取缓存;主要用在查找方法上。
@CachePut:修改缓存,如果不存在就创建;主要用在修改方法上。
@CacheEvict:删除缓存,当数据删除时,如果缓存还在,就必须删除;主要用在删除方法上。
注意:缓存的pojo类需要实现序列化