使用源码安装 Redis

安装前准备

以 redis-4.0.6 为例,实际使用时替换为需要的版本即可。

安装编译依赖:

> yum install -y gcc make

下载并解压:

> wget http://download.redis.io/releases/redis-4.0.6.tar.gz
> tar -zxvf redis-4.0.6.tar.gz
> cd redis-4.0.6

编译安装

> make
说明

Redis 4.x 默认使用自带的 jemalloc。如果编译 jemalloc 时出错,可改用系统内存分配器重新编译:make MALLOC=libc。

编译完成后进入 src 目录安装:

> cd src && make install

安装后会在 /usr/local/bin 下生成 redis-server、redis-cli、redis-benchmark 等命令。

编译报错:缺少 hiredis / lua 静态库
    LINK redis-server
cc: 错误:../deps/hiredis/libhiredis.a:没有那个文件或目录
cc: 错误:../deps/lua/src/liblua.a:没有那个文件或目录
make: *** [redis-server] 错误 1

回到源码目录下的 deps 目录,重新编译依赖后再安装:

> cd ../deps
> make hiredis lua linenoise
> cd ../src
> make install

配置与开机自启

创建配置目录,并复制配置文件:

> mkdir -p /etc/redis
> cp /root/redis-4.0.6/redis.conf /etc/redis/6379.conf

创建日志与数据目录:

> mkdir -p /var/log/redis /var/lib/redis

编辑 /etc/redis/6379.conf,至少确认以下几项:

/etc/redis/6379.conf
# 以守护进程方式运行,init 脚本依赖该配置
daemonize yes
# 日志文件
logfile "/var/log/redis/6379.log"
# RDB 数据文件存放目录
dir /var/lib/redis

复制启动脚本并赋权:

> cp /root/redis-4.0.6/utils/redis_init_script /etc/init.d/redisd
> chmod +x /etc/init.d/redisd

脚本默认读取 /etc/redis/${REDISPORT}.conf(即 /etc/redis/6379.conf),pid 文件为 /var/run/redis_6379.pid,与上面的配置一致。

设置开机自启:

> chkconfig redisd on
> systemctl daemon-reload    # 让 systemd 识别新增的 init 脚本
chkconfig 报错:服务不支持 chkconfig

提示 service redisd does not support chkconfig 或 服务 redisd 不支持 chkconfig 时,在 redisd 文件的 #!/bin/sh 之后加入两行注释,保存后再执行 chkconfig redisd on。

#!/bin/sh
# chkconfig:   2345 90 10
# description:  Redis is a persistent key-value database

启动并查看状态:

> systemctl start redisd
> systemctl status redisd
> systemctl stop redisd

验证安装

> redis-cli
127.0.0.1:6379> ping
PONG
127.0.0.1:6379> set name redis
OK
127.0.0.1:6379> get name
"redis"

默认没有密码,可以直接连接操作。生产环境不建议使用 keys *,可用 scan 分批遍历。

设置密码

编辑 /etc/redis/6379.conf,取消 requirepass 的注释并改为实际密码:

/etc/redis/6379.conf
requirepass 123456

重启后生效:

> systemctl restart redisd

连接时需要认证:

> redis-cli -a 123456
127.0.0.1:6379> auth 123456
OK
说明

redis-cli -a 会让密码出现在命令历史中,生产环境可先执行 redis-cli,再在交互界面执行 auth <密码>。

开放远程访问

默认只监听 127.0.0.1。需要远程访问时修改配置:

/etc/redis/6379.conf
# 监听所有网卡
bind 0.0.0.0
# 关闭保护模式
protected-mode no

放行防火墙端口:

> firewall-cmd --add-port=6379/tcp --permanent
> firewall-cmd --reload
Warning

Redis 暴露到公网极易被扫描攻击,务必设置强密码,并通过 firewall-cmd 或安全组限制来源 IP。

常用运维命令

> redis-server -v                        # 查看服务端版本
> redis-cli -a 123456 info server        # 查看服务信息
> redis-cli -a 123456 info memory        # 查看内存使用
> redis-cli -a 123456 info clients       # 查看连接数
> redis-cli -a 123456 dbsize             # 当前库 key 数量
> redis-cli -a 123456 config get maxmemory
> redis-cli -a 123456 config set maxmemory 512mb
> redis-cli -a 123456 shutdown           # 关闭服务

参考