Skip to content

在 CentOS / Rocky / AlmaLinux 等 RHEL 系服务器上使用 yum 安装 rpm 包

若系统为 Fedora 或已默认 dnf,把下面 yum 换成 dnf 即可(包名通常仍为 redis)。

安装流程

shell
# 使用 yum 安装 redis
yum -y install redis

# 启动 Redis 服务
systemctl start redis

# 设置 Redis 服务开机自启
systemctl enable redis

# 检查 Redis 服务状态
systemctl status redis # 如果安装成功并正在运行,你应该会看到类似 "active (running)" 的绿色状态提示。

# 连接到本地的 Redis 服务
redis-cli  # 或者,指定 ip 和 端口 redis-cli -h 127.0.0.1 -p 6379

# 可以设置一个键值对来测试
127.0.0.1:6379> set mykey "Hello, Redis!"
OK

# 获取刚才设置的值
127.0.0.1:6379> get mykey
"Hello, Redis!"

# 退出 Redis 命令行
127.0.0.1:6379> exit

yum 安装的 redis 常用命令

  1. 服务命令
shell
systemctl start redis    # 启动服务
systemctl reload redis   # 重新加载redis.conf配置文件
systemctl restart redis  # 重启服务
systemctl stop redis     # 停止服务

systemctl enable redis     # 开机自启
systemctl disable redis    # 开机不自启
systemctl list-unit-files | grep redis   # 检查redis是否已经安装了开机自动启动

systemctl status redis   # 查看redis状态

ps -ef | grep redis          # 查看进程redis进程
kill -9 pid                  # 杀掉 redis 进程
netstat -antlp | grep redis  # 查看redis服务端口

yum remove redis             # yum 卸载redis软件包
  1. redis 终端命令
shell
set key value
get key
keys *
del key

给 redis 设置密码

shell
# 查询配置文件位置
find / -name redis.conf

# 结果
/etc/redis.conf

# 修改配置文件
vim /etc/redis.conf

# 找到空白维护,插入如下内容,插入到最下方防止被覆盖,或者注释原来的(密码:MyRedis@123,关闭保护模式,允许外接访问,允许后台允许)
requirepass MyRedis@123
protected-mode no
bind 0.0.0.0
daemonize yes

# 重启 redis
systemctl restart redis

# 重启 服务
service redis restart

# 验证Redis服务是否启动成功
systemctl status redis

# 验证密码是否设置成功
redis-cli

keys * # (error) NOAUTH Authentication required.  # 提示未认证,说明密码生效

auth MyRedis@123
# 新版本默认username:default
keys *

配置防火墙

你的服务器启用了防火墙(如 firewalld),并且需要从外部访问 Redis,你需要开放 Redis 的端口(默认为 6379)。

shell
firewall-cmd --list-all   # 查看所有开放的端口/服务(默认 zone 为 public)
sudo firewall-cmd --zone=public --add-port=6379/tcp --permanent
sudo firewall-cmd --reload