一. 缓存的作用

当应用体积大了,用户量上去了,数据规模也越来越大之后,数据库查询操作将成为用户体验的瓶颈,这时使用缓存会是一个非常好的解决办法。Spring 开始从3.1 开始就为我们提供了基于注解的缓存支持,通过注解方式低侵入地为我们的应用提供缓存支持。在SpringBoot中,更是以一系列自动配置的方式使我们能更加方便的使用缓存功能。

二. 几个重要的注解

名称 解释
@EnableCaching 开启缓存注解
@Cacheable 主要针对方法配置,能够根据方法的请求参数对其结果进行缓存
@CachePut 保证方法被调用,又希望结果被缓存。
与@Cacheable区别在于是否每次都调用方法,常用于新增、更新
@CacheEvict 清空缓存

三. @Cacheeable/@CachePut/@CacheEvict 的几个常用参数

名称 解释 示例
value 缓存块的名称,必须指定一个 @Cacheable(value = " default ")
key 缓存的 key,可以为空,如果指定要按照 SpEL 表达式编写,
如果不指定,则缺省按照方法的所有参数进行组合
@Cacheable(value = " default ",key = " 'info' ")
@Cacheable(value = " default ",key = " #id ")
sync
(@Cacheable)
指示底层将缓存锁住,使只有一个线程可以进入计算,而其他线程堵塞,直到返回结果更新到缓存中。
可以避免缓存击穿
@Cacheable(value = " default ",sync = true)
allEntries
(@CacheEvict )
是否清空所有缓存内容,缺省为 false,如果指定为 true,则方法调用后将立即清空所有缓存 @CachEvict(value = ” default ”,allEntries = true)

四. 开始使用 – 整合 Redis

注: 需先启动 Redis 服务器

1. 导入 Maven 包

1
2
3
4
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

2. 配置 application.yml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
spring:
redis:
#指定Redis数据库索引,在redis-cli中使用select index切换数据库
database: 0
#Redis服务器地址
host: 127.0.0.1
#Redis连接端口,默认为 6379
port: 6379
#Redis连接密码,默认为空
password:
#连接超时时间
timeout: 0
#连接池
pool:
#最大连接数(使用负值表示没有限制)
max-acive: 1000
#最大阻塞等待时间
max-wait: -1
#最大空闲连接
max-idle: 10
#最小空闲连接
min-idle: 2

3. 在启动类上开启缓存注解

1
2
3
4
5
6
7
8
9
@SpringBootApplication
@EnableCaching // 开启缓存注解
public class AnimaApplication {

public static void main(String[] args) {
SpringApplication.run(AnimaApplication.class, args);
}

}

4. 缓存 @Cacheable

@Cacheable注解会先查询是否已经有缓存,有会使用缓存,没有则会执行方法并缓存。该注解还可预防缓存穿透。

1
2
3
4
5
6
7
8
/**
* key:可使用参数时,即 key#参数名,亦可直接使用字符串‘key’
* sync:避免缓存击穿
*/
@Cacheable(value = "default",key = " 'anima' + #page",sync = true)
public ArrayList<animaInfo> getAnimaInfo(int page,int limit) {
return animaInfoMapper.selectAnima(page,limit);
}

注:@Cacheable不支持设置缓存过期时间和自动更新

5. 更新 @CachePut

@CachePut标注的方法在执行前不会去检查缓存中是否存在之前执行过的结果,而是每次都会执行该方法,并将执行结果以键值对的形式存入指定的缓存中。

1
2
3
4
@CachePut(value = "default",key = " 'anima' + #anima.id")
public int save(Anima anima) {
return animaInfoMapper.saveAnima(anima);
}

6. 清除 @CacheEvict

allEntries参数表示是否需要清除缓存中的所有元素。默认为false,表示不需要。当指定了allEntries为true时,Spring Cache将忽略指定的key。有的时候我们需要Cache一下清除所有的元素。

1
2
3
4
@CacheEvict(value = "default",allEntries = true)
public int del(Anima anima) {
return animaInfoMapper.delAnima(anima.id);
}

评论