下面以 Linux + Nginx + MySQL + PHP(LNMP) 环境为例,系统讲解 Redis 的安装与配置,适用于 CentOS / Rocky / Alma / Ubuntu 常见发行版。
# 安装 EPEL(如果未安装)
yum install -y epel-release
# 安装 Redis
yum install -y redis
# 启动并设置开机自启
systemctl start redis
systemctl enable redis
apt update
apt install -y redis-server
# 启动
systemctl start redis
systemctl enable redis
yum install -y gcc make
cd /usr/local/src
wget https://download.redis.io/redis-stable.tar.gz
tar -zxvf redis-stable.tar.gz
cd redis-stable
make
make install
启动:
redis-server
redis-cli
127.0.0.1:6379> ping
PONG
✅ 返回 PONG 说明 Redis 正常运行。
/etc/redis.conf/etc/redis/redis.conf编辑:
vim /etc/redis.conf
bind 0.0.0.0
requirepass your_password
daemonize yes
maxmemory 512mb
maxmemory-policy allkeys-lru
重启 Redis:
systemctl restart redis
php -v
yum install -y php-pear php-devel
pecl install redis
安装完成后添加扩展:
echo "extension=redis.so" > /etc/php.d/redis.ini
apt install -y php-redis
systemctl restart php-fpm
php -m | grep redis
✅ 看到 redis 即成功。
<?php
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
$redis->auth('your_password'); // 如果设置了密码
$redis->set('test', 'hello redis');
echo $redis->get('test');
浏览器访问或命令行执行:
php test.php
✅ 缓存 MySQL 查询结果
✅ Session 存储
✅ 接口限流
✅ 队列(List / Stream)
bindfirewall-cmd --add-port=6379/tcp --permanent
firewall-cmd --reload
redis 扩展php-fpm 已重启LNMP 安装 Redis:系统装 Redis → 配密码 → PHP 装 redis 扩展 → 重启 PHP-FPM
如果你愿意,我可以:
直接告诉我你的 Linux 版本 + PHP 版本 即可。