以下是在CentOS LNMP環境中使用Redis的完整教程:
sudo yum install epel-release -y
sudo yum install redis -y
sudo systemctl start redis
sudo systemctl enable redis
sudo systemctl status redis # 驗證服務狀態
sudo yum install gcc make -y
wget https://download.redis.io/releases/redis-7.2.4.tar.gz
tar xzf redis-7.2.4.tar.gz
cd redis-7.2.4
make && sudo make install
(后續需手動配置redis.conf
并創建系統服務,參考官方文檔)修改配置文件
/etc/redis.conf
bind 127.0.0.1 # 僅本地訪問(生產環境建議限制IP)
port 6379
requirepass yourpassword # 設置密碼
maxmemory 1gb # 限制內存使用
maxmemory-policy allkeys-lru # 內存不足時淘汰策略
daemonize yes # 后臺運行
sudo systemctl restart redis
防火墻設置(如需遠程訪問)
sudo firewall-cmd --add-port=6379/tcp --permanent
sudo firewall-cmd --reload
sudo yum install php-pecl-redis -y
# 或通過PECL安裝(需先安裝php-pear)
# sudo pecl install redis
修改/etc/php.ini
,添加:
extension=redis.so
重啟PHP-FPM:sudo systemctl restart php-fpm
命令行測試
redis-cli -h 127.0.0.1 -p 6379 -a yourpassword
ping # 應返回 PONG
set test "Hello Redis"
get test # 應返回 "Hello Redis"
PHP代碼測試
<?php
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
$redis->auth('yourpassword');
$redis->set('php_key', 'Redis in PHP');
echo $redis->get('php_key');
?>
訪問PHP頁面,若顯示“Redis in PHP”則配置成功。
緩存數據庫查詢結果
// 偽代碼:先查Redis,未命中則查數據庫
$cacheKey = "product_{$productId}";
$data = $redis->get($cacheKey);
if (!$data) {
$data = $db->query("SELECT * FROM products WHERE id = {$productId}")->fetch();
$redis->setex($cacheKey, 3600, json_encode($data)); // 緩存1小時
}
return json_decode($data, true);
發布/訂閱模式
$redis->connect('127.0.0.1', 6379);
$redis->publish('news', 'Breaking news!');
$redis->connect('127.0.0.1', 6379);
$redis->subscribe(['news'], function($redis, $channel, $message) {
echo "Received: {$message}\n";
});
requirepass
)并限制IP訪問(bind
)。FLUSHALL
):rename-command FLUSHALL ""
。redis-cli info
redis-cli save
(RDB快照)或配置AOF持久化。以上步驟基于CentOS 7/8環境,如需適配其他版本請調整包管理命令。