一、基础连接配置(单机模式)
基础参数(适用Spring Boot)
spring:redis:host: 127.0.0.1port: 6379password: your_passworddatabase: 0 # 默认DB索引timeout: 2000ms # 全局操作超时时间
二、连接池参数(通用核心配置)
连接池详细配置(以Lettuce为例)
lettuce:pool:max-active: 200 # 最大活跃连接数(按QPS×响应时间计算)max-idle: 200 # 最大空闲连接数(建议与max-active一致)min-idle: 20 # 最小空闲连接预热连接数max-wait: 100ms # 获取连接最长等待时间test-while-idle: true # 开启空闲连接健康检测time-between-eviction-runs: 30s # 空闲连接检测周期
三、集群/哨兵模式配置
Redis Cluster配置示例
spring:redis:cluster:nodes:- 192.168.1.101:7001- 192.168.1.102:7002- 192.168.1.103:7003max-redirects: 3 # 最大重定向次数
哨兵模式配置
sentinel:master: mymasternodes:- 192.168.1.201:26379- 192.168.1.202:26379password: sentinel_pass
四、性能优化参数
properties
内核级优化(redis.conf)
maxmemory 16gb # 最大内存限制
maxmemory-policy volatile-lru # 内存淘汰策略
tcp-backlog 512 # 高并发连接队列长度
timeout 300 # 连接空闲超时(秒)
五、客户端配置模板
Jedis(Java原生)
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxTotal(200); // 最大连接数:ml-citation{ref="6" data="citationList"}
config.setMinIdle(20); // 最小空闲连接数:ml-citation{ref="1" data="citationList"}
config.setMaxWaitMillis(100); // 等待超时时间:ml-citation{ref="5" data="citationList"}
JedisPool pool = new JedisPool(config, "redis-host", 6379, 2000, "password");
Go-Redis
client := redis.NewClient(&redis.Options{Addr: "redis-host:6379",Password: "your_password",DB: 0,PoolSize: 200, // 连接池大小:ml-citation{ref="6" data="citationList"}MinIdleConns: 20, // 最小空闲连接数:ml-citation{ref="1" data="citationList"}PoolTimeout: 100 * time.Millisecond,
})
六、安全增强配置
yaml
生产环境安全建议
requirepass your_strong_password # 强制密码认证
rename-command FLUSHDB "" # 禁用高危命令
protected-mode yes # 开启保护模式
bind 127.0.0.1 192.168.1.0/24 # IP白名单限制
注释说明:
连接池参数需根据QPS × 平均响应时间动态计算(公式:max-active = QPS×响应时间(ms)/1000 + 冗余值)
集群模式下建议禁用testOnBorrow检测,优先通过testWhileIdle保障连接健康
内存分配策略推荐volatile-lru(对带过期时间的Key执行LRU淘汰)
通过此模板可快速搭建高可用、高性能的Redis服务,建议配合监控工具(如Prometheus)实时跟踪连接池状态和内存使用率。