Skip to content

第二章 安装与配置 v1.0 ​

一、安装Redis ​

  1. 下载Redis安装包
  2. 编译安装
  3. 配置redis.conf
  4. 启动Redis服务

二、连接Redis ​

bash
redis-cli

三、Linux安装(CentOS 7.6) ​

Redis在Linux系统上的安装,以CentOS 7.6为例。

1.下载并启动 ​

使用yum下载Redis:yum install redis

若没有反应,更新yum仓库:yum update

添加第三方源:EPEL

bash
systemctl start redis.service
systemctl status redis.service

2.修改配置 ​

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

text
daemonize yes  # 设置后台启动,如果不是后台启动,每次退出Redis会自动关闭
# 开启密码保护,注释则不需要密码
requirepass 密码
# 设置端口号
port 端口号(默认6379)
# 允许访问的IP,改为0.0.0.0就是所有IP均可
# bind 127.0.0.1 -::1
bind 0.0.0.0

更多配置项:Redis配置文件详解

3.设置开机自启动(此步跳过) ​

创建并修改文件:vim /usr/lib/systemd/system/redis.service

text
[Unit]
Description=Redis Server
After=network.target
[Service]
PIDFile=/var/run/redis_6379.pid
ExecStart=/usr/local/bin/redis-server /etc/redis.conf
ExecStop=/usr/local/bin/redis-cli -a passwd shutdown
ExecReload=/bin/kill -s HUP $MAINPID
[Install]
WantedBy=multi-user.target

4.重载并启动服务 ​

bash
systemctl enable redis.service
systemctl daemon-reload
systemctl start redis.service

5.相关报错解决 ​

bash
chown redis:redis /var/log/redis/redis.log

四、Redis服务操作 ​

bash
# 重载系统服务
systemctl daemon-reload
# 设置开机自启
systemctl enable redis.service
# 取消开机自启
systemctl disable redis.service
# 启动服务
systemctl start redis.service
# 停止服务
systemctl stop redis.service
# 查看服务状态
systemctl status redis.service

五、Redis连接与数据库操作 ​

bash
redis-cli  # 连接Redis基本语句
redis-cli -h host -p port -a password  # 指定密码远程连接Redis服务
text
redis 127.0.0.1:6379> PING
PONG
redis 127.0.0.1:6379> QUIT
redis 127.0.0.1:6379> SELECT index_number
redis 127.0.0.1:6379> CONFIG SET requirepass "password"
redis 127.0.0.1:6379> AUTH password
bash
select <index>  # 切换数据库
dbsize  # 查看当前数据库的key数量
flushdb  # 清空当前数据库
flushall  # 清空所有数据库