距离上次更新本文已经过去了 386 天,文章部分内容可能已经过时,请注意甄别

安装和启动

plaintext
1
sudo apt install -y redis

安装了之后使用如下方式启动 redis

plaintext
1
sudo systemctl start redis

看一下 6379 端口号是否有进程在监听,有代表启动成功了

plaintext
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
[root:/etc/redis]# systemctl status redis
● redis-server.service - Advanced key-value store
Loaded: loaded (/lib/systemd/system/redis-server.service; enabled; vendor preset: enabled)
Active: active (running) since Sat 2024-02-10 14:45:11 CST; 4min 56s ago
Docs: http://redis.io/documentation,
man:redis-server(1)
Main PID: 1350 (redis-server)
Status: "Ready to accept connections"
Tasks: 5 (limit: 9527)
Memory: 7.5M
CGroup: /system.slice/redis-server.service
└─1350 "/usr/bin/redis-server 127.0.0.1:6379" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" >

Feb 10 14:45:11 wsl-ubuntu systemd[1]: Starting Advanced key-value store...
Feb 10 14:45:11 wsl-ubuntu systemd[1]: Started Advanced key-value store.
[root:/etc/redis]# netstat -nltp | grep 6379
tcp 0 0 127.0.0.1:6379 0.0.0.0:* LISTEN 1350/redis-server 1
tcp6 0 0 ::1:6379 :::* LISTEN 1350/redis-server 1

注意,如果你尝试在子用户里用如下命令查看 redis 是否绑定成功端口,可能查询不到结果。

plaintext
1
netstat -nltp | grep redis

因为在子用户中,我们看不到当前占用 6379 端口的进程名字。只有 root 用户能看到。

允许远程访问

默认情况下 redis 绑定的 ip 是 127.0.0.1,这个 ip 地址只允许本机访问,即你只能在这台 linux 主机上访问这个 redis。

如果想实现远程访问,我们需要将绑定的 ip 改成 0.0.0.0,并且关闭远程访问的保护

使用如下命令切换到 root 用户

plaintext
1
sudo su - 

进入 redis 的配置文件路径

plaintext
1
cd /etc/redis

这里有一个 redis.conf 配置文件,我们需要修改的是下面的条目

plaintext
1
2
bind 127.0.0.1 ::1
protected-mode yes

将它们修改为如下所示,即启用了 redis 允许远程访问的模式。

plaintext
1
2
bind 0.0.0.0 ::1
protected-mode no

修改完毕配置文件后,重启服务器即可生效

plaintext
1
sudo systemctl restart redis

连接 redis

和 MySQL 一样,Redis 也是客户 - 服务端架构的软件。在 Linux 中,使用 redis-cli 命令即可直接连到当前主机的 redis 服务器

plaintext
1
2
3
4
[root:/etc/redis]# redis-cli
127.0.0.1:6379> ping
PONG
127.0.0.1:6379>

如果需要链接非本机的 redis 服务器,使用如下命令:

bash
1
redis-cli -h IP地址 -p 端口

如果想让 redis-cli 中可以正常显示中文,可以添加 --raw 选项。注意:使用该选项会导致 Redis 中显示的 (nil) 变成空字符串,极易产生误导!如果不是硬性需要在控制台中显示中文,请不要使用该选项!

plaintext
1
redis-cli --raw

当然,我们也可以像 MySQL 一样使用 C 语言的开发包来链接 redis,那是后话了。

命令学习

redis 的命令学习可以参考官网 Commands | Redis

虽然是英文文档,但是照着翻译读读差不多都能看明白是怎么用的。