温馨提示×

centos redis连接怎么配置

小樊
44
2026-09-08 21:34:36
栏目: 云计算

在 CentOS 上配置 Redis 连接,通常分为 Redis 服务端配置客户端连接方式 两部分。下面按常见使用场景说明。


一、Redis 安装(CentOS)

# 安装 EPEL(如未安装)
sudo yum install -y epel-release

# 安装 Redis
sudo yum install -y redis

# 启动 Redis
sudo systemctl start redis

# 开机自启
sudo systemctl enable redis

检查是否运行:

redis-cli ping
# 返回 PONG 表示正常

二、Redis 服务端连接配置(redis.conf)

配置文件位置一般是:

/etc/redis.conf

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

bind 127.0.0.1

改为(允许所有 IP):

bind 0.0.0.0

或指定 IP:

bind 127.0.0.1 192.168.1.100

⚠️ 生产环境不建议直接 0.0.0.0,应配合防火墙和安全组。


2️⃣ 关闭保护模式(仅测试环境)

protected-mode yes

改为:

protected-mode no

3️⃣ 设置密码(推荐)

requirepass yourpassword

连接时需:

redis-cli -a yourpassword

4️⃣ 修改端口(可选)

port 6379

修改后重启:

sudo systemctl restart redis

三、防火墙配置(CentOS 7+)

# 开放 6379 端口
sudo firewall-cmd --permanent --add-port=6379/tcp
sudo firewall-cmd --reload

四、客户端连接方式

1️⃣ 本地连接

redis-cli

2️⃣ 指定 IP + 端口

redis-cli -h 192.168.1.100 -p 6379

3️⃣ 带密码连接

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

五、程序连接示例

Java(Spring Boot)

spring:
  redis:
    host: 192.168.1.100
    port: 6379
    password: yourpassword

Python

import redis

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

print(r.ping())

六、常见问题

连接被拒绝

  • Redis 未启动
  • bind 限制
  • 防火墙未开放端口

NOAUTH Authentication required

  • 未输入密码或密码错误

Could not connect

  • protected-mode 未关闭
  • 云服务器安全组未放行

如果你能说明:

  • 本地 / 远程
  • 是否 云服务器
  • 使用 哪种语言/框架

我可以给你更精准的配置示例。

0