在 CentOS 上搭建 LNMP(Linux + Nginx + MySQL + PHP) 环境后,安装 Redis 一般有两步:
1️⃣ 安装 Redis 服务
2️⃣ 安装 PHP 的 Redis 扩展(让 PHP 能连 Redis)
下面以 CentOS 7 / 8 为例说明(假设你已装好 LNMP)。
# CentOS 7
yum install epel-release -y
yum install redis -y
# CentOS 8
dnf install redis -y
启动并设置开机自启:
systemctl start redis
systemctl enable redis
检查是否运行:
redis-cli ping
# 返回 PONG 表示成功
yum install gcc make -y
cd /usr/local/src
wget https://download.redis.io/redis-stable.tar.gz
tar xzf redis-stable.tar.gz
cd redis-stable
make
make install
启动:
redis-server /usr/local/src/redis-stable/redis.conf
yum install php-devel php-pear gcc make -y
pecl install redis
安装完成后,在 php.ini 中添加:
extension=redis.so
重启 PHP:
systemctl restart php-fpm
cd /root/lnmp1.x
./addons.sh
选择 redis 安装即可(自动装扩展)。
新建测试文件 test.php:
<?php
phpinfo();
浏览器访问,搜索 redis,看到 redis 模块即成功。
或用命令:
php -m | grep redis
<?php
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
$redis->set('test', 'hello redis');
echo $redis->get('test');
编辑 redis.conf:
bind 0.0.0.0
protected-mode no
重启:
systemctl restart redis
firewall-cmd --add-port=6379/tcp --permanent
firewall-cmd --reload
如果你告诉我:
我可以给你更精准的命令。