springboot缓存

如果没有引入其他缓存依赖时,springboot默认使用ConcurrenMapCacheManager作为缓存管理器
本文介绍使用redis缓存

引入依赖

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

配置

1
2
3
4
5
6
7
8
9
10
11
12
spring:
redis:
#地址
host: localhost
#端口
port: 6379
#索引库
database: 0
#密码
password:
cache:
type: redis

开启缓存

1
2
3
4
5
6
7
8
@EnableCaching
@SpringBootApplication
public class MyApplication {

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

缓存

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
@Service
public class TestService {

/**
* 如果缓存中有则直接走缓存,如果没有则执行方法,将方法的返回值作为缓存
*/
@Cacheable(value = "cache-test", key = "#p0")
public String getName(long id){
System.out.println("等待3秒。。。。");
try {
Thread.sleep(3000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
return id + ":name";
}

/**
* 将方法的返回值更新到缓存
*/
@CachePut(value = "cache-test", key = "#p0")
public String updateName(long id){
System.out.println("更新名称");
return id + ":nickname";
}

/**
* 删除缓存
* @CacheEvict(value = "cache-test", allEntries = true)
* allEntries:方法执行完之后将缓存名称为cache-test的所有缓存删除
*/
@CacheEvict(value = "cache-test", key = "#p0")
public void deleteName(long id){
System.out.println("删除名称");
}
}
  1. @Cacheable:获取缓存
    value:缓存名称,必须有,spring根据value进行分组
    key: 缓存的key,支持spel表达式,如果没有则按照方法的所有参数进行组合

  2. @CachePut:更新缓存
    value和key与@Cacheabl的value和key相同

  3. @CacheEvict:删除缓存
    value和key与@Cacheabl的value和key相同