一、基礎連接配置(單機模式)
基礎參數(適用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)實時跟蹤連接池狀態和內存使用率。