Redis 作為高效能鍵值存儲,廣泛用於快取、Session、佇列、排行榜等場景。本文詳細記錄 Linux 上從源碼編譯安裝 Redis、解決 jemalloc 編譯錯誤、配置系統服務、基本安全加固與效能調優全流程。
# 安裝編譯工具鏈
# RHEL/CentOS/Rocky/Alma
sudo dnf install gcc gcc-c++ make tcl
# Ubuntu/Debian
sudo apt install build-essential tcl
VERSION=7.2.5
wget https://download.redis.io/releases/redis-${VERSION}.tar.gz
tar xzf redis-${VERSION}.tar.gz
cd redis-${VERSION}
make MALLOC=libc
# 或永久生效
echo "MALLOC=libc" >> .make.settings
make
原理: Redis 預設使用 jemalloc,部分舊版核心/glibc 環境缺少 jemalloc 開發頭文件導致編譯失敗 (jemalloc/jemalloc.h: No such file or directory)。指定 MALLOC=libc 改用系統 glibc malloc,犧牲少量記憶體碎片管理效能,換取編譯通過與相容性。
make test
# 需安裝 tcl,耗時 1-2 分鐘,全綠通過表示穩定
sudo make install PREFIX=/usr/local/redis
# 預設安裝到 /usr/local/bin,PREFIX 可自訂
sudo mkdir -p /etc/redis /var/lib/redis /var/log/redis
sudo cp redis.conf /etc/redis/redis.conf
sudo chown -R redis:redis /var/lib/redis /var/log/redis # 需先建立 redis 使用者
/etc/redis/redis.conf):
bind 127.0.0.1 -::1 # 僅監聽本地,生產環境按需放開
port 6379
daemonize yes # 守護進程模式
pidfile /var/run/redis/redis.pid
logfile /var/log/redis/redis.log
dir /var/lib/redis # RDB/AOF 檔案目錄
appendonly yes # 開啟 AOF 持久化
appendfsync everysec # 平衡效能與安全
maxmemory 2gb # 記憶體上限,按機器配置
maxmemory-policy allkeys-lru # 淘汰策略
requirepass YourStrongPass # 必設密碼
rename-command FLUSHDB "" # 禁用危險命令
rename-command FLUSHALL ""
rename-command KEYS ""
/etc/systemd/system/redis.service):
[Unit]
Description=Redis In-Memory Data Store
After=network.target
[Service]
Type=notify
User=redis
Group=redis
ExecStart=/usr/local/redis/bin/redis-server /etc/redis/redis.conf
ExecStop=/usr/local/redis/bin/redis-cli shutdown
Restart=on-failure
LimitNOFILE=65535
[Install]
WantedBy=multi-user.target
sudo useradd -r -s /sbin/nologin -M redis
sudo systemctl daemon-reload
sudo systemctl enable --now redis
sudo systemctl status redis
| 錯誤現象 | 原因 | 解決 |
|---|---|---|
jemalloc/jemalloc.h: No such file | 缺少 jemalloc-devel | make MALLOC=libc 或 dnf install jemalloc-devel |
Newer version of jemalloc required | 系統 jemalloc 版本過舊 | make MALLOC=libc (推薦) |
Can't open config file | 配置檔路徑錯誤 | 確認 -c /etc/redis/redis.conf 或 CONFIG_FILE 環境變數 |
Permission denied 啟動失敗 | 目錄權限/SELinux | chown -R redis:redis /var/lib/redis /var/log/redis;setsebool -P redis_enable_notify on |
max number of clients reached | 連線數超限 | 調大 maxclients、檢查連線洩漏、使用連線池 |
| OOM killer 終止進程 | 記憶體不足 | 設定 maxmemory、啟用 swap、調整 vm.overcommit_memory=1 |
requirepassbindFLUSHALL、KEYS、CONFIG)tls-port、tls-cert-file)maxmemory + 淘汰策略# 內建基準工具
redis-benchmark -h 127.0.0.1 -p 6379 -a YourPass -n 100000 -c 50 -t set,get
# -n 總請求數 -c 並發連線 -t 測試命令類型
遵循本指南,可在 Linux 上構建穩定、安全、高效能的 Redis 服務節點,為上層業務提供可靠的資料基礎設施。