当系统的访问量增大时,相应的数据库的性能就逐渐下降。但是,大多数请求都是在重复的获取相同的数据,如果使用缓存,将结果数据放入其中可以很大程度上减轻数据库的负担,提升系统的响应速度。
声明式缓存
Spring 定义 CacheManager 和 Cache 接口用来统一不同的缓存技术。例如 JCache、 EhCache、 Hazelcast、 Guava、 Redis 等。在使用 Spring 集成 Cache 的时候,我们需要注册实现的 CacheManager 的 Bean。
Spring Boot 为我们自动配置了 JcacheCacheConfiguration、 EhCacheCacheConfiguration、HazelcastCacheConfiguration、GuavaCacheConfiguration、RedisCacheConfiguration、SimpleCacheConfiguration 等。所以下面学习中ehcache和redis中无需在配置,若是其他cache,则需先注册。
springboot默认采用ConcurrenMapCacheManager作为缓存管理器,即不使用其他第三方缓存的时候用该类。
Spring Boot 针对不同的缓存技术实现了不同的封装,本篇主要介绍 EhCache、Redis和spring cache 缓存。
Spring Boot 提供了以下几个注解实现声明式缓存:
注解 | 说明 |
---|---|
@EnableCaching | 开启缓存功能,放在配置类或启动类上 |
@CacheConfig | 缓存配置,设置缓存名称 |
@Cacheable | 执行方法前先查询缓存是否有数据。有则直接返回缓存数据;否则查询数据再将数据放入缓存 |
@CachePut | 执行新增或更新方法后,将数据放入缓存中 |
@CacheEvict | 清除缓存(将一条或多条数据从缓存中删除, 主要用于删除方法,用来从缓存中移除相应数据) |
@Caching | 将多个缓存操作重新组合到一个方法中 |
1.spring cache
在springboot中默认使用spring cache做缓存。
1.1添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
1.2实现
具体实现与ehcache的实现类似。
2.ehcache缓存
2.1.添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
</dependency>
2.2添加配置
1)在 src/main/resources 目录下创建 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">
<!-- 磁盘缓存位置 -->
<diskStore path="java.io.tmpdir/ehcache"/>
<