温馨提示×

Centos Redis怎么配置

小樊
45
2026-07-20 02:28:06
栏目: 云计算

下面分常见场景给你讲一下 CentOS 上 Redis 的配置方法,从安装到常用配置项,基本覆盖 90% 的实际情况。


一、在 CentOS 上安装 Redis

方式一:使用 yum(推荐,简单)

yum install -y epel-release
yum install -y redis

安装完成后:

redis-server --version

方式二:编译安装(版本更新)

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 配置文件位置

  • yum 安装

    /etc/redis.conf
    
  • 编译安装

    /usr/local/src/redis-stable/redis.conf
    

建议拷贝一份再改:

cp /etc/redis.conf /etc/redis.conf.bak

三、Redis 常用配置说明(重点)

编辑配置文件:

vim /etc/redis.conf

1️⃣ 绑定 IP(安全很重要)

默认:

bind 127.0.0.1

✅ 只允许本机访问(推荐)
❌ 允许所有 IP 访问(危险):

bind 0.0.0.0

2️⃣ 设置密码(强烈建议)

requirepass your_password

连接时需要密码:

redis-cli -a your_password

3️⃣ 以守护进程方式运行

daemonize yes

4️⃣ 端口配置

port 6379

可改成其他端口,提高安全性。


5️⃣ 持久化配置

RDB(快照)

save 900 1
save 300 10
save 60 10000

AOF(推荐)

appendonly yes
appendfsync everysec

6️⃣ 最大内存限制

maxmemory 512mb
maxmemory-policy allkeys-lru

防止 Redis 把服务器内存吃光。


7️⃣ 日志和数据库文件

logfile /var/log/redis/redis.log
dir /var/lib/redis

四、启动 / 停止 / 开机自启

yum 安装方式

systemctl start redis
systemctl enable redis
systemctl status redis

编译安装方式

redis-server /etc/redis.conf

或写 systemd 服务(推荐)。


五、防火墙 & 安全设置

打开端口(如果是远程访问)

firewall-cmd --add-port=6379/tcp --permanent
firewall-cmd --reload

⚠️ 不建议直接暴露 Redis 到公网


六、测试 Redis 是否可用

redis-cli
ping
# 返回 PONG

设置 / 获取值:

set name centos
get name

七、生产环境推荐配置总结 ✅

bind 127.0.0.1
requirepass 你的密码
daemonize yes
appendonly yes
maxmemory 1gb
maxmemory-policy allkeys-lru

如果你可以告诉我:

  • ✅ CentOS 7 还是 8?
  • ✅ Redis 是否要远程访问?
  • ✅ 是否用于生产环境?

我可以直接给你一套最合适的完整配置

0