Redis在SpringBoot中的简单使用

一、导入依赖

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

二、后台代码

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
@RestController
@RequestMapping("/kind")
public class KindController {

@Autowired
private KindService kindService;

@Autowired
RedisTemplate redisTemplate;

static String REDIS_KIND_LIST = "kind_list";
@GetMapping("/list")
public List<Kind> list(){
//从Redis中获取分类数据
// listOperations对集合进行操作
ListOperations listOperations = redisTemplate.opsForList();
Long size = listOperations.size(REDIS_KIND_LIST);
if (size != null && size > 0){
//如果Redis中存在分类数据,直接返回Redis中分类数据
List list = listOperations.range(REDIS_KIND_LIST, 0, size - 1);
return list;
}else {
//如果Redis中不存在分类数据,从数据库中取出分类数据
List<Kind> list = kindService.list();
//将分类数据存储在Redis中,并返回
listOperations.rightPushAll(REDIS_KIND_LIST,list);
return list;
}

}
}

image

三、序列化问题导致存储在Redis显示非中文

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
package org.yunfree.toutiao202302.config;


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.yunfree.toutiao202302.modle.Kind;

import java.net.UnknownHostException;

import java.awt.print.Book;

@Configuration
public class RedisConfig {

@Bean
public RedisTemplate<String, Kind> redisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
RedisTemplate<String, Kind> template = new RedisTemplate();
template.setConnectionFactory(redisConnectionFactory);
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Kind.class);
template.setDefaultSerializer(jackson2JsonRedisSerializer);
return template;
}

}

image


Redis在SpringBoot中的简单使用
https://yunfreehh.github.io/2023/03/27/Redis在SpringBoot中的简单使用/
作者
yunfree
发布于
2023年3月27日
许可协议