Redis-RedisTemplate

redis连接池配置

  • 添加maven依赖
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<exclusions>
<exclusion>
<groupId>io.lettuce</groupId>
<artifactId>lettuce-core</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
  • 添加配置文件,设置redis连接池
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
spring:
redis:
client-type: jedis
host: 192.168.80.128
password: aacopy.cn
port: 6379
jedis:
pool:
# 连接池最大连接数,默认为8
max-active: 100
# 最大空闲连接数, 默认为8
max-idle: 100
# 最小空闲连接数,默认为0,设置最大最小相同,空间换时间,避免创建tcp握手耗时
min-idle: 100
# 连接池最大阻塞等待时间,默认-1,表示没有限制
max-wait: 60000

设置序列化规则

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
@Configuration
public class RedisTemplateConfig {

@Bean
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(redisConnectionFactory);
//配置序列化规则
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);

ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
jackson2JsonRedisSerializer.setObjectMapper(objectMapper);

//设置key-value序列化规则
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);

//设置hash-value序列化规则
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);

return redisTemplate;
}
}