Spring Boot 整合 Redis

Redis

配置文件

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

Redis的配置文件集中在RedisProperties中,配置文件中以spring.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
29
@ConfigurationProperties(prefix = "spring.redis")
public class RedisProperties {
private int database = 0; //使用的数据库下标
private String host = "localhost";
private String password;
private int port = 6379;
private boolean ssl;
private Duration timeout; //超时时间
private RedisProperties.Sentinel sentinel; //哨兵模式
private RedisProperties.Cluster cluster; //集群模式

public static class Sentinel {
private String master;
private List<String> nodes;
}

public static class Cluster {
private List<String> nodes;
private Integer maxRedirects;
}

public static class Pool {
private int maxIdle = 8;
private int minIdle = 0;
private int maxActive = 8;
private Duration maxWait = Duration.ofMillis(-1L);
private Duration timeBetweenEvictionRuns;
}
}
1
2
3
4
#application.properties
spring.redis.host= localhost
spring.redis.port=6379
spring.redis.password=

自动配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
@Configuration
@ConditionalOnClass(RedisOperations.class)
@EnableConfigurationProperties(RedisProperties.class)
@Import({ LettuceConnectionConfiguration.class, JedisConnectionConfiguration.class })
public class RedisAutoConfiguration {

@Bean
@ConditionalOnMissingBean(name = "redisTemplate")
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory)
throws UnknownHostException {
RedisTemplate<Object, Object> template = new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory);
return template;
}

@Bean
@ConditionalOnMissingBean
public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory)
throws UnknownHostException {
StringRedisTemplate template = new StringRedisTemplate();
template.setConnectionFactory(redisConnectionFactory);
return template;
}
}

可以看到RedisAutoConfiguration默认创建两个Bean,其中创建了一个主要以String类型操作的stringRedisTemplate,也就是说可以直接通过注解使用这些Bean

RedisAutoConfiguration初始化两个Bean时使用了@ConditionalOnMissingBean注解,如果我们想要自己实现初始化Bean,只需要自行编写个配置类注入Bean组件即可。

序列化

redisTemplate如果保存的是对象时,默认使用JdkSerializationRedisSerializer类作为序列化机制,将对象序列化后的数据(非明文)存储到redis数据库中。Redis规定序列化机制的实现类需要实现RedisSerializer接口。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public interface RedisSerializer<T> {

@Nullable
static RedisSerializer<Object> java(@Nullable ClassLoader classLoader) {
return new JdkSerializationRedisSerializer(classLoader);
}

static RedisSerializer<Object> json() {
return new GenericJackson2JsonRedisSerializer();
}

static RedisSerializer<String> string() {
return StringRedisSerializer.UTF_8;
}
}

在不配置的情况下,默认JDK序列化机制,普遍情况下,我们习惯把对象以String或者JSON的结构存储到Redis,这时候需要手动配置序列化机制,而只要我们引入了相关的依赖包,如FastJson,就能够找到对应的序列化器FastJsonRedisSerializer

redis-1

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

//手动配置redisTemplate
@Bean
public RedisTemplate<Object, Object> redisTemplate(
RedisConnectionFactory redisConnectionFactory)
throws UnknownHostException {
RedisTemplate<Object, Object> template = new RedisTemplate<Object, Object>();
template.setConnectionFactory(redisConnectionFactory);
FastJsonRedisSerializer<Object> ser = new FastJsonRedisSerializer<Object>(Object.class);
//设置默认序列化器,对所有的key-value类型都生效
template.setDefaultSerializer(ser);
return template;
}
}

测试

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
37
38
39
40
41
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootApplicationTests {
@Autowired
EmployeeMapper employeeMapper;

@Autowired
StringRedisTemplate stringRedisTemplate; //操作k-v都是字符串的

@Autowired
RedisTemplate redisTemplate; //k-v都是对象的


/**
* Redis常见的五大数据类型
* String(字符串)、List(列表)、Set(集合)、Hash(散列)、ZSet(有序集合)
* stringRedisTemplate.opsForValue()[String(字符串)]
* stringRedisTemplate.opsForList()[List(列表)]
* stringRedisTemplate.opsForSet()[Set(集合)]
* stringRedisTemplate.opsForHash()[Hash(散列)]
* stringRedisTemplate.opsForZSet()[ZSet(有序集合)]
*/
@Test
public void test01(){
//给redis中保存数据
stringRedisTemplate.opsForValue().append("msg","hello");
String msg = stringRedisTemplate.opsForValue().get("msg");
System.out.println(msg);

stringRedisTemplate.opsForList().leftPush("mylist","1");
stringRedisTemplate.opsForList().leftPush("mylist","2");
}

//测试保存对象
@Test
public void test02(){
Employee emp = new Employee("张三","男");
//默认如果保存对象,使用jdk序列化机制,序列化后的数据保存到redis中
//配置redisTemplate的序列化机制,将对象数据以JSON的方式保存
redisTemplate.opsForValue().set("emp-01",emp);
}

最后更新: 2020年12月29日 22:25

原始链接: https://midkuro.gitee.io/2020/05/27/springboot-redis/

× 请我吃糖~
打赏二维码