Redis整合SpringBoot

一、SpringBoot整合Redis

1.1 导入Maven

1
2
3
4
5
6
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<version>2.6.7</version>
</dependency>

1.2 配置Redis连接

1
2
3
4
5
6
7
8
9
10
11
12
spring:
redis:
client-type: jedis #客户端类型
host: localhost
port: 6379
jedis:
pool:
enabled: true
max-active: 20 # 连接池最大连接数(使用负值表示没有限制)
max-idle: 10 # 连接池中的最大空闲连接
min-idle: 5 # 连接池中的最小空闲连接
max-wait: 1000ms # 连接池最大阻塞等待时间(使用负值表示没有限制)

1.3 定制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
30
31
32
33
34
@Configuration
public class RedisConfig {
/**
* redis序列化配置
*
* @param redisConnectionFactory redis连接工厂
* @return redisTemplate
*/
@Bean
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
// 配置redisTemplate
RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(redisConnectionFactory);
// 设置序列化
Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
jackson2JsonRedisSerializer.setObjectMapper(om);
// key序列化
redisTemplate.setKeySerializer(new StringRedisSerializer());
// value序列化
redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
// Hash key序列化
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
// Hash value序列化
redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
redisTemplate.afterPropertiesSet();
//开启事务支持
// redisTemplate.setEnableTransactionSupport(true);
return redisTemplate;
}
}

二、整合Redission

2.1 导入Maven

1
2
3
4
5
6
<!--引入redisso客户端依赖-->
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson</artifactId>
<version>3.17.0</version>
</dependency>

2.2 自定义配置Redisson

1
2
3
4
5
6
7
8
9
10
11
12
13
@Configuration
public class RedissionConfig {
@Bean(destroyMethod = "shutdown")
public RedissonClient redisson() throws IOException {
Config config = new Config();
//单节点模式
//Redis url should start with redis:// or rediss:// (for SSL connection)
//可以用"rediss://"来启用SSL连接
config.useSingleServer()
.setAddress("redis://127.0.0.1:6379");
return Redisson.create(config);
}
}