以下是在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环境,如需适配其他版本请调整包管理命令。