准备工作
环境:Ubuntu 20.04
Redis版本:5.0.7
安装 Redis
Redis 软件包在 UbUbuntu 20.04 默认在设置的软件源中,执行命令:
sudo apt update
sudo apt install redis-server
安装完成后,Redis的服务会自动启动,检查服务的状态,执行命令:
sudo systemctl status redis-server
正常启动时,应该看到下面的内容:
● redis-server.service - Advanced key-value store
Loaded: loaded (/lib/systemd/system/redis-server.service; enabled; vendor preset: enabled)
Active: active (running) since Sat 2020-06-06 20:03:08 UTC; 10s ago
...
如果没有正常启动,查看 IPV6 设置,执行命令:
vim /etc/default/ufw
修改 IPV6 的设置为true,如下图所示:
# Set to yes to apply rules to support IPv6 (no means only IPv6 on loopback
# accepted). You will need to 'disable' and then 'enable' the firewall for
# the changes to take affect.
IPV6=yes
如果是使用的 WSL ( Windows Subsystem for Linux ) 适用于 Linux 的Windows 子系统,安装的 Ubuntu 20.04,执行检查服务状态的命令提示:
System has not been booted with systemd as init system (PID 1). Can't operate.
Failed to connect to bus: Host is down
原因是因为 WSL2 没有 systemd 命令 ,可以执行命令:
sudo service redis-server status
正常启动 Redis 显示的内容:
* redis-server is running
配置 Redis 远程访问
默认情况下,Redis不允许远程连接,仅仅能通过127.0.0.1(localhost)连接 Redis 服务器 - Redis 正在运行的机器上。
如果使用的是单机器,数据库也在这台机器上,不需要配置远程访问。
配置 Redis 远程访问 ,执行命令:
vim /etc/redis/redis.conf
打开 Redis 配置文件后,找到以下内容:
# for connections from all the network interfaces available on the server.
# It is possible to listen to just one or multiple selected interfaces using
# the "bind" configuration directive, followed by one or more IP addresses.
#
# Examples:
#
# bind 127.0.0.1 ::1
#
# ~~~ WARNING ~~~ If the computer running Redis is directly exposed to the
# internet, binding to all the interfaces is dangerous and will expose the
# instance to everybody on the internet. So by default we uncomment the
# following bind directive, that will force Redis to listen only into
# the IPv4 loopback interface address (this means Redis will be able to
# accept connections only from clients running into the same computer it
# is running).
#
# IF YOU ARE SURE YOU WANT YOUR INSTANCE TO LISTEN TO ALL THE INTERFACES
# JUST COMMENT THE FOLLOWING LINE.
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
bind 127.0.0.1 ::1
根据配置文件注释,增加以下 IP 地址:
bind 0.0.0.0 ::1
保存配置文件,重启 Redis 服务,执行命令:
sudo systemctl restart redis-server
sudo service redis-server restart
为什么有两条命令,上面已经讲过了。
检查 Redis 监听的端口,执行命令:
ss -an | grep 6379
正常启动,应该会看到下面的内容:
tcp LISTEN 0 128 0.0.0.0:6379 0.0.0.0:*
tcp LISTEN 0 128 [::1]:6379 [::]:*
配置防火墙,允许网络通过 TCP 端口 6379
允许从一个指定 IP 地址或者一个指定 IP 范围来访问 Redis 服务器。例如,想要允许从192.168.121.0/24的连接,执行命令:
sudo ufw allow proto tcp from 192.168.121.0/24 to any port 6379
确保你的防火墙被配置仅仅接受来自受信任 IP 的连接。
到了这里,Redis的远程设置已经完成。
验证 Redis 远程配置是否成功,在远程服务器上使用 redis-cli Ping 一下 Redis 服务器,执行命令:
redis-cli -h ping
正常响应的结果,如下面所示:
PONG
启动 redis 服务器后,打开终端并输入命令 redis-cli,该命令会连接本地的 redis 服务。执行命令:
redis-cli
127.0.0.1:6379> ping
PONG
注意:执行 Redis 命令需要 Redis客户端。 redis-cli 是 Redis 的客户端,在下载的 Redis 安装包里面。
Redis 文档
了解更多的 Redis 使用,可以访问 Redis 官网!