1、添加依赖

1
2
3
4
5
6
7
8
9
10
11
12
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>

2、添加redis配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
spring:
redis:
#数据库索引
database: 2
host: 127.0.0.1
port: 6379
password: abcd123
jedis:
pool:
max-active: 8
max-wait: -1ms
max-idle: 8
min-idle: 0
timeout: 300s

3、注入CacheManager

既然是用redis,当然要注入RedisCacheManager ,redis缓存管理器。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@Configuration
public class RedisConfig extends CachingConfigurerSupport {

@Bean
public RedisCacheManager cacheManager(RedisConnectionFactory factory) {
return RedisCacheManager.create(factory);
}

@Bean
public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, String> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(factory);
return redisTemplate;
}
}

4、具体使用

简单来说,主要有三个注解

  1. @Cacheable 表示将返回结果缓存到redis,key值为dict::
    “#p0”表示取第一个参数,如果参数为对象,则可以通过#p0.id获取对象的id

  2. @CacheEvict表示删除该缓存数据

  3. @CachePut表示修改该缓存数据

1
2
3
4
5
6
7
8
@ApiOperation(value = "获取字典详情", notes = "根据id获取字典")
@ApiImplicitParam(name = "id", value = "字典ID", required = true, dataType = "String", paramType = "query")
@RequestMapping(value = "get-by-id", method = RequestMethod.GET)
@Cacheable(value = "dict", key = "#p0")
public ResultModel<PtDict> getById(@RequestParam("id") String id) {
System.out.println("开始获取id为【" + id + "】的字典");
return new ResultModel<>(ResultStatus.SUCCESS, dictService.selectById(id));
}

5、缓存结果

请求两次上面的controller,返回结果如下:

  1. 结果被缓存到redis
  2. 第二次请求时候没有输出“开始获取id为【58ce515474cd454fb6266f49a01833c0】的字典”,因为此时数据已从redis获取
img
img

img

转自:https://www.jianshu.com/p/8b026187dc62