目標:部署一主兩從3哨兵的模式
按照企業級標準設置redis參數(對redis.conf做基礎設置、安全設置、內存設置、持久化等參數)
步驟:
- 操作系統設置主機名、進程數限制、依賴包安裝、源、關閉防火牆、對時等。
- redis下載,解壓,編譯安裝。
- 做成systemd服務管理。
- 配置主從。
- 配置哨兵模式。
- 測試數據同步、主從切換。
系統基礎設置
機器列表
- 主節點:192.168.68.132/24,同時也是哨兵節點
- 從節點:192.168.68.131/24,同時也是哨兵節點
- 從節點:192.168.68.133/24,同時也是哨兵節點
3個節點源、安裝依賴
[redis@Rocky1 ~]$ cat /etc/yum.repos.d/aliyun.repo
[baseos-aliyun]
name=Rocky Linux $releasever - BaseOS
baseurl=https://mirrors.aliyun.com/rockylinux/$releasever/BaseOS/$basearch/os/
gpgcheck=0
enabled=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-rockyofficial
[appstream-aliyun]
name=Rocky Linux $releasever - AppStream
baseurl=https://mirrors.aliyun.com/rockylinux/$releasever/AppStream/$basearch/os/
gpgcheck=0
enabled=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-rockyofficial
[extras-aliyun]
name=Rocky Linux $releasever - Extras
baseurl=https://mirrors.aliyun.com/rockylinux/$releasever/extras/$basearch/os/
gpgcheck=0
enabled=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-rockyofficial
[crb-aliyun]
name=Rocky Linux $releasever - CRB
baseurl=https://mirrors.aliyun.com/rockylinux/$releasever/CRB/$basearch/os/
gpgcheck=0
enabled=1
gpgkey=file:///etc/pki/rpm/gpg/RPM-GPG-KEY-rockyofficial
[redis@Rocky1 ~]$
yum install -y gcc tcl
#優化文件描述符和進程限制
[root@Rocky1 ~]# cat /etc/security/limits.conf
* soft nproc 655350
* hard nproc 655350
* soft nofile 655350
* hard nofile 655350
#主機名、防火牆、對時自行關閉
安裝redis
- 用二進制tar包安裝,所有節點一樣,不一樣的地方是配置文件參數。
tar xzf redis-6.2.6.tar.gz
mv /root/redis/redis-6.2.6/ /usr/local/src/redis
cd /usr/local/src/redis
#安裝沒有指定具體目錄,一些命令會安裝在默認系統目錄/usr/local/bin
make && make install
cp redis.conf /etc/redis.conf
配置主從
其實是配置ip地址、日誌、密碼、最大連接數、最大限制內存、內存回收策略、持久化、慢查詢設置等
- 主從配置可以用命令,也可以寫在配置文件,我們直接寫到配置文件,將來如果主從發生改變,要同步修改配置文件。
主節點配置文件
有些參數是系統自帶默認
[root@Rocky2 ~]# grep -v '#' /etc/redis.conf
bind 0.0.0.0
protected-mode no
port 6379
tcp-backlog 511
timeout 300
tcp-keepalive 300
#systemd沒使用Type=forking管理,我使用Type=simple管理,也能夠看到日誌,只要日誌的級別是詳細才可以看到登錄的時候日誌。
daemonize no
#如果systemd沒使用Type=forking 管理redis服務,用的是Type=simple,不需要pid
#pidfile /run/redis.pid
loglevel notice
logfile "/var/log/redis/redis-server.log"
syslog-enabled yes
databases 16
always-show-logo no
#工作目錄
dir /usr/local/src/redis/
replica-serve-stale-data yes
replica-read-only yes
repl-diskless-sync no
repl-diskless-sync-delay 5
repl-diskless-load disabled
repl-disable-tcp-nodelay no
replica-priority 100
acllog-max-len 128
requirepass 123456
maxclients 100000
#我的電腦是32G限制redis使用16G,你根據自己電腦的情況下,一般分配內存的%50-80給
maxmemory 16gb
maxmemory-policy allkeys-lru
maxmemory-samples 10
lazyfree-lazy-eviction yes
lazyfree-lazy-expire yes
lazyfree-lazy-server-del yes
replica-lazy-flush yes
lazyfree-lazy-user-del no
lazyfree-lazy-user-flush no
disable-thp yes
appendonly yes
appendfilename "appendonly.aof"
appendfsync everysec
no-appendfsync-on-rewrite no
auto-aof-rewrite-percentage 100
auto-aof-rewrite-min-size 64mb
aof-load-truncated yes
aof-use-rdb-preamble yes
lua-time-limit 5000
slowlog-log-slower-than 10000
slowlog-max-len 128
latency-monitor-threshold 0
notify-keyspace-events ""
hash-max-ziplist-entries 512
hash-max-ziplist-value 64
list-max-ziplist-size -2
list-compress-depth 0
client-output-buffer-limit normal 0 0 0
client-output-buffer-limit replica 256mb 64mb 60
client-output-buffer-limit pubsub 32mb 8mb 60
redis.conf參數解析
# 配置文件詳細説明
################################## 基礎配置 ###################################
# 是否以守護進程方式運行Redis
# yes: 後台運行。
# no: 前台運行,適合調試,但是systemd啓動redis,用的是前台運行會看不到日誌,沒有在日誌文件生成。
daemonize yes
# Redis監聽端口,默認6379
port 6379
# 綁定的IP地址
# 0.0.0.0: 監聽所有網絡接口
# 127.0.0.1: 只監聽本地迴環地址
bind 0.0.0.0
# 保護模式,防止外部網絡未經授權訪問
# yes: 如果沒有設置密碼和bind,只允許本地訪問
# no: 關閉保護模式
protected-mode yes
# TCP連接隊列長度,高併發場景需要調整
# 511: 默認值,Linux中最大可以是511
tcp-backlog 511
# 客户端空閒超時時間(秒),0表示不超時
timeout 3600
# TCP心跳包間隔時間(秒),用於保持連接
tcp-keepalive 300
################################# 安全配置 ###################################
# Redis訪問密碼,生產環境必須設置
# 格式: requirepass "複雜密碼"
requirepass "YourStrongPasswordHere"
# 禁用危險命令或重命名,防止誤操作,不設置。
# 重命名SHUTDOWN命令,增加操作難度,不設置。
################################# 性能優化 ###################################
# 最大客户端連接數
maxclients 1000000
# 異步釋放內存,減少阻塞
# 在內存回收、過期鍵刪除、服務器刪除時使用異步操作
lazyfree-lazy-eviction yes
lazyfree-lazy-expire yes
lazyfree-lazy-server-del yes
replica-lazy-flush yes
################################# 內存管理 ###################################
# 最大內存限制,根據服務器物理內存的70%-80%設置
# 示例: 16GB內存的服務器可設置為12-13GB
maxmemory 16gb
# 內存淘汰策略,當內存達到maxmemory時的處理方式
# allkeys-lru: 所有鍵中最近最少使用的鍵優先淘汰
# volatile-lru: 只從設置了過期時間的鍵中淘汰
# volatile-lfu -> 驅逐過期key中最少頻繁使用
# allkeys-lfu -> 驅逐所有key中最少頻繁使用
# allkeys-random: 隨機淘汰
# volatile-random: 從設置了過期時間的鍵中隨機淘汰
# volatile-ttl: 淘汰過期時間最小的鍵
# noeviction: 不淘汰,返回錯誤(默認)
# LRU means Least Recently Used
# LFU means Least Frequently Used
maxmemory-policy allkeys-lru
# 隨機採樣的樣本數量,用於LRU算法
# 值越大越精確,但CPU消耗也越大
maxmemory-samples 10
############################## AOF持久化配置 ################################
# 啓用AOF持久化
appendonly yes
# AOF文件名
appendfilename "appendonly.aof"
# AOF文件同步策略
# always: 每次寫操作都同步,最安全但性能最差
# everysec: 每秒同步一次,性能與安全的平衡(推薦)
# no: 由操作系統決定何時同步,性能最好但可能丟失數據
appendfsync everysec
# 重寫期間是否停止fsync
# yes: 重寫期間停止同步,提高性能但可能丟失數據
# no: 重寫期間繼續同步,保證數據安全(推薦)
no-appendfsync-on-rewrite no
# AOF自動重寫觸發條件
# 當前AOF文件大小比上次重寫後的大小增長的比例
# 100表示增長100%時觸發重寫
auto-aof-rewrite-percentage 100
# AOF自動重寫最小文件大小
# AOF文件達到64MB時才考慮重寫
auto-aof-rewrite-min-size 64mb
# 加載被截斷的AOF文件時是否繼續
# yes: 繼續加載,可能丟失部分數據
# no: 停止加載,需要手動修復
aof-load-truncated yes
# AOF重寫時使用RDB格式的序言
# yes: 重寫時先以RDB格式寫入,再追加AOF,提高性能和壓縮率(推薦)
# no: 純AOF格式
aof-use-rdb-preamble yes
# AOF重寫時增量式fsync
# yes: 每32MB數據執行一次fsync,避免單次大文件fsync阻塞
# no: 整個文件重寫完成後執行fsync
aof-rewrite-incremental-fsync yes
############################## 高級AOF配置 ################################
# AOF重寫最小觸發大小
aof-rewrite-min-size 64mb
# AOF是否添加時間戳
# yes: 添加,便於調試但增加文件大小
# no: 不添加(推薦)
aof-timestamp-enabled no
# 是否禁用AOF自動垃圾回收
# yes: 禁用,需要手動執行BGREWRITEAOF
# no: 啓用自動重寫(推薦)
aof-disable-auto-gc no
############################## 日誌配置 ###################################
# 日誌級別
# debug: 調試信息,非常詳細
# verbose: 詳細信息
# notice: 普通信息,適合生產環境(推薦)
# warning: 只記錄警告和錯誤
loglevel notice
# 日誌文件路徑
logfile "/var/log/redis/redis-server.log"
# 是否使用系統日誌
# yes: 使用系統syslog
# no: 使用文件日誌(推薦)
syslog-enabled no
############################## 慢查詢日誌 ################################
# 慢查詢閾值(微秒)
# 10000 = 10毫秒,超過這個時間的查詢會被記錄
slowlog-log-slower-than 10000
# 慢查詢日誌最大條數
# 只保留最近的128條慢查詢
slowlog-max-len 128
############################## 客户端配置 ################################
# 普通客户端輸出緩衝區限制
# 格式:hard limit soft limit soft seconds
# 0表示無限制
client-output-buffer-limit normal 0 0 0
# 從節點客户端輸出緩衝區限制
# 256mb硬限制,64mb軟限制,60秒軟限制時間
client-output-buffer-limit replica 256mb 64mb 60
# 發佈訂閲客户端輸出緩衝區限制
client-output-buffer-limit pubsub 32mb 8mb 60
############################## 主從複製配置 ###############################
# 從節點是否繼續服務舊數據
# yes: 當主從同步中斷時,從節點繼續提供舊數據
# no: 只提供最新數據
replica-serve-stale-data yes
# 從節點是否只讀
# yes: 從節點只讀,不能寫入(推薦)
# no: 可寫入,但寫入的數據會在同步時丟失
replica-read-only yes
# 是否使用無盤複製
# yes: 主節點直接將RDB通過網絡發送給從節點,節省磁盤I/O
# no: 先寫入磁盤再發送(推薦,更穩定)
repl-diskless-sync no
# 無盤複製延遲時間(秒)
# 等待更多從節點連接後再開始同步
repl-diskless-sync-delay 5
# 是否禁用TCP_NODELAY
# yes: 禁用,減少包數量但增加延遲
# no: 啓用,減少複製延遲(推薦)
repl-disable-tcp-nodelay no
# 從節點優先級,用於選舉新主節點
# 值越小優先級越高,0表示永遠不會被選為主節點
replica-priority 100
############################## 集羣配置 ###################################
沒做集羣配置
############################## 監控 #######################################
# 延遲監控閾值(毫秒)
# 超過100毫秒的操作會被監控
latency-monitor-threshold 100
############################## 事件通知 ###################################
# 鍵空間事件通知
# 為空表示不啓用,具體配置參考Redis文檔
notify-keyspace-events ""
############################## 內核優化 ###################################
# 是否調整OOM分數
# yes: 調整,讓Redis進程在OOM時更不容易被殺死
# no: 不調整
oom-score-adj no
# OOM分數調整值
oom-score-adj-values 0 200 800
############################## 操作系統交互 ###############################
# 進程監管方式
# systemd: 使用systemd管理,用systemd管理服務。其實寫systemd也可以創建systemd文件,也可以啓動redis,
# 只是只是看到redis的狀態,一些更細的參數看不到,不過沒關係,我們看日誌就行。
# systemd方式在redis6.2的時候,需要手動編譯該參數默認是不支持,會在日誌
# 看到systemd supervision requested or auto-detected, but Redis is compiled without libsystemd support!
# upstart: 使用upstart管理
# auto: 自動檢測
# no: 不監管
supervised systemd
############################## 網絡優化 ###################################
# 複製積壓緩衝區大小
# 用於部分重新同步
repl-backlog-size 1mb
# 複製積壓緩衝區過期時間(秒)
repl-backlog-ttl 3600
############################## Lua腳本 ###################################
默認
############################## 主從複製安全性 ############################
# 主節點密碼,用於從節點連接認證
masterauth "123456"
# 設置為主節點的從節點
# replicaof <主節點IP> <主節點端口>
# replicaof <masterip> <masterport>
############################## 連接限制 ###################################
# 客户端查詢緩衝區最大限制
client-query-buffer-limit 1gb
# 協議最大批量長度
proto-max-bulk-len 512mb
############################## TLS配置 ###################################
默認
############################## AOF自動修復 ###############################
# AOF文件同步模式詳細設置
aof-fsync-always no
aof-fsync-everysec yes
aof-fsync-no no
############################## 內存碎片整理 ###############################
# 是否啓用主動內存碎片整理
activedefrag yes
# 忽略的內存碎片大小
active-defrag-ignore-bytes 100mb
# 內存碎片整理閾值下限
active-defrag-threshold-lower 10
# 內存碎片整理閾值上限
active-defrag-threshold-upper 100
# 碎片整理最小CPU使用率
active-defrag-cycle-min 5
# 碎片整理最大CPU使用率
active-defrag-cycle-max 75
############################## 進程標題 ###################################
# 設置進程標題
set-proc-title yes
# 進程標題模板
proc-title-template "{title} {listen-addr} {server-mode}"
############################## 模塊配置 ###################################
# 加載Redis模塊
# loadmodule /path/to/mymodule.so
################################## 使用説明 ###################################
# 重要配置步驟:
# 1. 必須修改項目:
# - requirepass: 設置強密碼
# - dir: 確保目錄存在且有權限
# - maxmemory: 根據服務器內存設置
# - bind: 根據網絡環境調整
# - protected-mode: 根據安全需求設置
#
# 2. 目錄權限設置:
# mkdir -p /var/lib/redis /var/log/redis
# chown redis:redis /var/lib/redis /var/log/redis
# chmod 755 /var/lib/redis /var/log/redis
#
# 3. 系統參數優化:
# echo never > /sys/kernel/mm/transparent_hugepage/enabled
# echo 511 > /proc/sys/net/core/somaxconn
# sysctl vm.overcommit_memory=1
#
# 4. AOF監控建議:
# - 監控AOF文件大小:redis-cli info persistence | grep aof_current_size
# - 監控AOF重寫狀態:redis-cli info persistence | grep aof_rewrite
# - 監控持久化延遲:redis-cli info stats | grep latest_fork_usec
#
# 5. 備份策略:
# - 每天備份AOF文件到異地
# - 定期執行BGREWRITEAOF壓縮文件
# - 監控磁盤空間使用
#
# 6. 故障恢復:
# - AOF文件損壞時,使用redis-check-aof --fix修復
# - RDB文件損壞時,可能無法修復
# - 定期測試備份文件的可用性
#
# 7. 性能調優:
# - 根據業務特點調整maxmemory-policy
# - 高併發場景調整tcp-backlog
# - 大量數據時調整client-output-buffer-limit
#
# 8. 安全建議:
# - 定期更換密碼
# - 使用防火牆限制訪問IP
# - 啓用TLS加密傳輸
# - 禁用危險命令
從節點1配置文件
和主節點配置文件區別:設置了主庫的ip地址和端口,密碼。
[root@Rocky1 redis]#vi /etc/redis.conf
bind 0.0.0.0
protected-mode no
port 6379
tcp-backlog 511
timeout 3600
tcp-keepalive 300
daemonize no
#如果systemd沒使用Type=forking 管理redis服務,用的是Type=simple,不需要pid
#pidfile /run/redis.pid
loglevel notice
logfile "/var/log/redis/redis-server.log"
syslog-enabled no
databases 16
always-show-logo no
replica-priority 100
acllog-max-len 128
requirepass 123456
maxclients 100000
maxmemory 16gb
maxmemory-policy allkeys-lru
maxmemory-samples 10
lazyfree-lazy-eviction yes
lazyfree-lazy-expire yes
lazyfree-lazy-server-del yes
replica-lazy-flush yes
lazyfree-lazy-user-del no
lazyfree-lazy-user-flush no
oom-score-adj no
oom-score-adj-values 0 200 800
appendonly yes
appendfilename "appendonly.aof"
appendfsync everysec
no-appendfsync-on-rewrite no
auto-aof-rewrite-percentage 100
auto-aof-rewrite-min-size 64mb
aof-load-truncated yes
aof-use-rdb-preamble yes
slowlog-log-slower-than 10000
slowlog-max-len 128
latency-monitor-threshold 100
client-output-buffer-limit normal 0 0 0
client-output-buffer-limit replica 256mb 64mb 60
client-output-buffer-limit pubsub 32mb 8mb 60
aof-rewrite-incremental-fsync yes
rdb-save-incremental-fsync yes
從節點2配置文件
和從節點1配置文件一模一樣(監聽地址要寫0.0.0.0,如果寫具體ip要修改)
systemd服務啓動redis
創建一個redis用户,那麼redis的目錄都屬主都是redis用户。
#如果你們公司沒要求用root用户,就用root(大多公司沒限制),免得各種資源限制權限不足。
#能用root,沒必要用普通用户。
adduser redis
chage -M 99999 redis
visudo #開通sudo
chown redis.redis -R /usr/local/src/redis/
chown redis.redis /etc/redis.conf
#日誌目錄
mkdir /var/log/redis
chown redis.redis /var/log/redis/
[root@Rocky2 ~]# cat /etc/systemd/system/redis.service
# /etc/systemd/system/redis.service
[Unit]
Description=Redis In-Memory Data Store
After=network.target
[Service]
# 使用專門的redis用户和組運行以提升安全性
User=redis
Group=redis
# 設置Type為simple
Type=simple
#和/etc/redis.conf配置的pid一致,Type=forking的時候才需要pid
#PIDFile=/run/redis/redis.pid
# 啓動和停止命令
ExecStart=/usr/local/bin/redis-server /etc/redis.conf
ExecStop=/usr/local/bin/redis-cli -a 123456 shutdown
# 配置進程意外退出時自動重啓[citation:2]
Restart=on-failure
TimeoutStartSec=300
# 重啓等待時間
RestartSec=3
LimitNOFILE=65535
LimitNPROC=65535
[Install]
WantedBy=multi-user.target
#啓動redis
systemctl daemon-reload
systemctl enable redis.service
systemctl start redis.service
檢查主從:
- 在主節點查看同步狀態
#主節點是master角色
[root@Rocky2 ~]# redis-cli
127.0.0.1:6379> auth 123456
OK
127.0.0.1:6379> ping
PONG
127.0.0.1:6379> info replication
# Replication
role:master
connected_slaves:2
slave0:ip=192.168.68.131,port=6379,state=online,offset=1964,lag=1
slave1:ip=192.168.68.133,port=6379,state=online,offset=1964,lag=0
master_failover_state:no-failover
master_replid:7255d28a6790c31a33e567616532535b5ef06e3e
master_replid2:0000000000000000000000000000000000000000
master_repl_offset:1964
second_repl_offset:-1
repl_backlog_active:1
repl_backlog_size:1048576
repl_backlog_first_byte_offset:1
repl_backlog_histlen:1964
#從節點執行,是slave角色
[root@Rocky3 redis]# redis-cli
127.0.0.1:6379> auth 123456
OK
127.0.0.1:6379> info replication
# Replication
role:slave
master_host:192.168.68.132
master_port:6379
master_link_status:up
master_last_io_seconds_ago:4
master_sync_in_progress:0
slave_read_repl_offset:2146
slave_repl_offset:2146
slave_priority:100
slave_read_only:1
replica_announced:1
connected_slaves:0
master_failover_state:no-failover
- 在主節點創建一個key,看下從節點有沒有數據。
主節點操作:
192.168.1.10:6379> SET test_key "hello_from_master"
在從節點讀取:
192.168.1.11:6379> GET test_key
- 從節點創建key,看下是不是隻讀,創建失敗。
- 檢查配置文件相關參數是不是正確讀到。
#檢查內存是不是配置文件設置的標準
127.0.0.1:6379> info memory
# Memory
maxmemory_human:16.00G #看到最大內存限制16G,是配置文件設置的標準
faq
Dec 11 11:01:53 Rocky1 systemd[1]: redis.service: Can't open PID file /run/redis/redis.pid (yet?) after start: Operation not permitted
答:systemd監管讀取/run/redis/redis.pid失敗,初步懷疑是redis在編譯的時候,沒加支持systemd參數(後面有空研究),systemd的文件已經用root用户,redis.conf配置了pid路徑。systemctl cate redis設置了user用户,是用來啓動redis進程的,不是systemd獲取進程的用户權限。
這個告警不影響redis的服務使用。
安裝哨兵
哨兵默認沒有leader,只有故障觸發的時候才會選舉leader。
創建sentinel.conf文件。
- 注意:每個節點ip不一樣。
- 哨兵節點1配置文件不需要寫節點2、節點3的ip,他們是通過監控同一個master,從而發現對端,節點之間會起一個頻道,通過頻道進行相互通信,節點1發現節點2和3以後,會自動添加配置到redis-sentinel.conf文件最後。
[root@Rocky2 ~]# mkdir /redis-sentinel
[root@Rocky2 ~]# chown redis.redis /redis-sentinel/
[root@Rocky2 ~]# chown redis.redis /etc/redis-sentinel.conf
[root@Rocky2 ~]# cat /etc/redis-sentinel.conf
# 哨兵服務端口,默認26379
port 26379
#通告地址
sentinel announce-ip "192.168.68.132"
# 守護進程模式運行(必須,以便systemd管理)
daemonize yes
# 進程PID文件
pidfile "/usr/local/src/redis/redis-sentinel.pid"
# 日誌文件路徑
logfile "/var/log/redis/redis-sentinel.log"
# 工作目錄,會創建一些臨時文件,放到tmp目錄下
dir "/redis-sentinel"
# 核心配置:監控名為“mymaster”的主節點。
# 參數依次為:主節點別名、IP、端口、法定人數(quorum)。
# 當至少2個(quorum值)哨兵主觀認為主節點下線時,才會客觀判定其下線並觸發故障轉移。
sentinel monitor mymaster 192.168.68.132 6379 2
# 主觀下線判定時間(毫秒),超過此時間無響應則主觀認為該節點下線
sentinel down-after-milliseconds mymaster 5000
# 故障轉移超時時間(毫秒)
#sentinel failover-timeout mymaster 60000
# 故障轉移後,每次同時向新主節點同步數據的從節點數量(設為1更平穩)
# 如果Redis主從節點配置了密碼(requirepass),這裏必須配置相同的密碼
sentinel auth-pass mymaster 123456
# 關閉保護模式,允許其他哨兵節點和客户端訪問
protected-mode no
redis-sentinel.conf下面內容,redis-sentinel啓動服務後自動加的配置,其實是發現還有其它哨兵,把這些哨兵ip和id都加上,不需要去管它。
# 關閉保護模式,允許其他哨兵節點和客户端訪問
protected-mode no
# Generated by CONFIG REWRITE
user default on nopass ~* &* +@all
sentinel myid 005f311b938333ef0fc1c1e4379ad44f8876c583
sentinel config-epoch mymaster 0
sentinel leader-epoch mymaster 0
sentinel current-epoch 0
sentinel known-replica mymaster 192.168.68.133 6379
sentinel known-replica mymaster 192.168.68.131 6379
sentinel known-sentinel mymaster 192.168.68.131 26379 f93d79997390b15bb64d9e5fda1348e9c141cdf6
sentinel known-sentinel mymaster 192.168.68.132 26379 258f26208faa8bb8ff15adbec45bb3c31adbc5c8
[root@Rocky3 ~]#
配置systemd服務啓動文件
[root@Rocky2 ~]# systemctl cat redis-sentinel.service
# /etc/systemd/system/redis-sentinel.service
[Unit]
Description=Redis Sentinel
# 通常在Redis服務啓動後啓動
After=network.target redis.service
Wants=redis.service
[Service]
User=root
Group=root
Type=forking
#和redis-sentinel.conf保持一致
PIDFile=/usr/local/src/redis/redis-sentinel.pid
# 注意:確保路徑 /usr/local/bin/redis-sentinel 是你實際的哨兵程序安裝路徑
ExecStart=/usr/local/bin/redis-sentinel /etc/redis-sentinel.conf --sentinel
ExecStop=/usr/local/bin/redis-cli -p 26379 shutdown
# 啓動後修正權限(讓 systemd 可以讀取)
ExecStartPost=/bin/chmod 777 /usr/local/src/redis/redis-sentinel.pid
ExecStartPost=/bin/chown redis:redis /usr/local/src/redis/redis-sentinel.pid
Restart=always
RestartSec=10
#要寫,有些系統不限制了,systemd還會限制。
LimitNOFILE=65535
LimitNPROC=65535
[Install]
WantedBy=multi-user.target
啓動哨兵
systemctl daemon-reload
systemctl enable redis-sentinel.service
systemctl start redis-sentinel.service
less /var/log/redis/redis-sentinel.log #查看日誌有沒有報錯
ss -antl
測試
[root@Rocky3 ~]# redis-cli -p 26379
127.0.0.1:26379>
127.0.0.1:26379> ping
PONG
127.0.0.1:26379> info sentinel
# Sentinel
sentinel_masters:1
sentinel_tilt:0
sentinel_running_scripts:0
sentinel_scripts_queue_length:0
sentinel_simulate_failure_flags:0
master0:name=mymaster,status=ok,address=192.168.68.132:6379,slaves=2,sentinels=2
127.0.0.1:26379>
127.0.0.1:26379> info sentinel
# Sentinel
sentinel_masters:1
sentinel_tilt:0
sentinel_running_scripts:0
sentinel_scripts_queue_length:0
sentinel_simulate_failure_flags:0
master0:name=mymaster,status=ok,address=192.168.68.132:6379,slaves=2,sentinels=3 #3個哨兵,2個
FAQ
啓動哨兵報錯:
WARNING: Sentinel was not able to save the new configuration on disk!!!: Permission denied
+slave slave 192.168.68.133:6379 192.168.68.133 6379 @ mymaster 192.168.68.132 6379
Could not create tmp config file (Permission denied)
答:redis-senntinel.conf參數dir修改,自己創建個目錄修改屬主屬組。若還不行,service文件啓動用户設置root啓動進程,經過測試不會報錯。
故障切換測試
演練:
- 把當前redis 的主節點服務關閉,讓它切換到從節點,
- 然後再啓動redis服務(此時會作為從加入到集羣)。
- 把新的主節點服務關閉,再切換一次,會有新的redis從節點成為主。
節點3操作,從節點查看此時還是slave角色:
[root@Rocky3 ~]# redis-cli -a 123456 info replication
Warning: Using a password with '-a' or '-u' option on the command line interface may not be safe.
# Replication
role:slave
master_host:192.168.68.132
master_port:6379
master_link_status:up
節點2操作:systemctl stop redis,一開始是主節點
節點3查看,發現變成成了主節點:
[root@Rocky3 ~]# redis-cli -a 123456 info replication
Warning: Using a password with '-a' or '-u' option on the command line interface may not be safe.
# Replication
role:master
connected_slaves:1
slave0:ip=192.168.68.131,port=6379,state=online,offset=1680981,lag=0
master_failover_state:no-failover
節點2啓動服務systemctl start redis,發現報錯:MASTER aborted replication with an error: NOAUTH Authentication required. 此時節點2作為從節點去連接主節點,配置文件redis.conf沒有寫主節點的密碼,因此要加上參數“
masterauth 123456
注意:節點2重啓後知道自動找到master節點去連接,其實是因為掛機的時候,本機有記錄文件,緩存記錄文件發現。
節點3查看,此時看到有2個slave節點:
[root@Rocky3 ~]# redis-cli -a 123456 info replication
Warning: Using a password with '-a' or '-u' option on the command line interface may not be safe.
# Replication
role:master
connected_slaves:2
slave0:ip=192.168.68.131,port=6379,state=online,offset=1881376,lag=0
slave1:ip=192.168.68.132,port=6379,state=online,offset=1881233,lag=0
驗證完成。