一、POM配置依赖包如下:
<!-- spring boot starter data redis 依赖 (lettuce配合 commons-pool2 对象池) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
二、连接Redis服务配置
1、方式一(推荐此方式)
spring:
redis:
host: xxx # Redis服务器地址
port: 6379 # Redis服务器连接端口
password: 123456 # Redis服务器连接密码(默认为空)
database: 0 # Redis数据库索引(默认为0)
timeout: 60s # 连接空闲超过N(s秒、ms毫秒)后关闭,0为禁用,这里配置值和tcp-keepalive值一致
# 默认使用 lettuce 连接池
lettuce:
pool:
max-active: 10 # 允许最大连接数,默认8(负值表示没有限制)
max-idle: 8 # 最大空闲连接数,默认8
min-idle: 0 # 最小空闲连接数,默认0
max-wait: 5s # 连接用完时,新的请求等待时间(s秒、ms毫秒),超过该时间抛出异常JedisConnectionException,(默认-1,负值表示没有限制)
#time-between-eviction-runs: 1s
推荐连接池参数规则(cpu指核数):
1、max-active:大于cpu * 2,通常为(cpu * 2) + 2
2、max-idle:cpu * 2
3、min-idle:0
4、max-wait:5s(秒)
5、time-between-eviction-runs:1s(秒)
注意:
1、推荐 lettuce 连接池,线程安全并且支持异步非阻塞请求
2、合理配置 lettuce 连接池参数,一般不会出现过段时间就断开连接的现象