温馨提示×

centos redis连接如何配置

小樊
39
2026-09-14 23:42:47
栏目: 云计算

CentOS 上配置 Redis 连接,通常包含 服务端配置(redis.conf)客户端连接方式 两部分。下面按常见场景说明。


一、安装 Redis(CentOS 7/8)

# CentOS 7
yum install epel-release -y
yum install redis -y

# CentOS 8
dnf install redis -y

启动并设置开机自启:

systemctl start redis
systemctl enable redis

二、Redis 服务端配置(关键)

配置文件路径:

/etc/redis.conf

1️⃣ 允许远程连接(默认只允许本机)

bind 0.0.0.0

⚠️ 生产环境建议绑定具体 IP,不要直接 0.0.0.0

2️⃣ 设置访问密码(推荐)

requirepass yourpassword

3️⃣ 关闭保护模式(远程连接时必须)

protected-mode no

4️⃣ 修改端口(可选)

port 6379

修改后重启:

systemctl restart redis

三、防火墙配置(非常重要)

开放 Redis 端口

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

四、客户端连接方式

1️⃣ 本机连接

redis-cli

带密码:

redis-cli -a yourpassword

2️⃣ 远程连接

redis-cli -h 192.168.1.100 -p 6379 -a yourpassword

3️⃣ 程序连接示例

Java(Jedis)

Jedis jedis = new Jedis("192.168.1.100", 6379);
jedis.auth("yourpassword");
jedis.set("key", "value");

Python

import redis

r = redis.Redis(
    host='192.168.1.100',
    port=6379,
    password='yourpassword',
    decode_responses=True
)

print(r.get('key'))

五、常见问题排查

❌ 连接被拒绝

  • redis 未启动
  • bind 限制
  • 防火墙未开放

❌ 提示 protected-mode

  • 设置 protected-mode no
  • 或配置密码 + bind

❌ 超时

  • 网络不通
  • 云服务器安全组未放行 6379

六、生产环境建议

✅ 使用密码
✅ 限制 IP(bind + 防火墙)
✅ 不使用默认端口(可选)
✅ 公网 Redis 强烈不推荐


如果你能提供:

  • CentOS 版本
  • 是否是云服务器
  • 本地还是远程连接

我可以给你更精确的配置方案

0