Redis的安装,配置和使用

Redis 是什么?

说到Redis,我们的第一印象肯定是作为缓存中间件使用了,这样想可能太片面,我们按官网的介绍来看吧(http://www.redis.cn/),全面的认识下它的用途和功能

image-20211204142501295

这里的描述很简练和清晰了,因此,打算梳理的 Redis 相关知识点如下:

  • Redis 支持丰富的数据类型,每种类型的特点及应用场景;
  • Redis 支持持久化机制,有RDB、AOF等持久化方式;
  • Redis 多机数据库的实现,有复制(replication)、哨兵(Sentinel)和集群(cluster)等功能;
  • Redis 支持事务,Redis事务的ACID特性;
  • Redis 支持的其他独立功能,如发布/订阅、慢日志查询、Lua脚本、排序及二进制位数组等;
  • Redis 不仅仅是缓存中间件,也可以当做nosql数据库、消息队列等使用。

当然了,Redis 的优势也有必要说明一下,比如:

  • 读写性能很好,Redis能读的速度是110000次/s,写的速度是81000次/s,原因有多路复用机制、Resp协议、单线程、基于内存持久化操作等;
  • 数据结构丰富,Redis不仅支持strings、lists、hashes、sets、sorted sets等5种基本数据结构,也支持bitmaps、hyperLogLogs、geospatial等复杂数据结构;
  • 所有操作原子性,所有 Redis 的操作都是原子的,能确保当多个客户同时访问 Redis 服务器时,每个用户得到的是更新后的最新值;
  • 拥有多样的特性,比如:支持多种键过期删除策略、支持多机数据库的实现(主从复制、哨兵和集群等)、可当做消息队列使用等。

同时,Redis 作为缓存使用时,缺点也很明显,会出现以下几种问题:

  • 缓存和数据库双写一致性问题;
  • 缓存雪崩问题;
  • 缓存击穿问题;
  • 缓存的并发竞争问题。

而这些问题也都有对应的解决方法

关于Redis的数据持久化

Redis的所有数据都是保存在内存中,然后不定期的通过异步方式保存到磁盘上(这称为“半持久化模式”);也可以把每一次数据变化都写入到一个append only file(aof)里面(这称为“全持久化模式”)。

由于Redis的数据都存放在内存中,如果没有配置持久化,redis重启后数据就全丢失了,于是需要开启redis的持久化功能,将数据保存到磁盘上,当redis重启后,可以从磁盘中恢复数据。redis提供两种方式进行持久化,一种是RDB持久化(原理是将Reids在内存中的数据库记录定时dump到磁盘上的RDB持久化),另外一种是AOF(append only file)持久化(原理是将Reids的操作日志以追加的方式写入文件)。

Redis版本选择及新版本特性

Redis 版本选择和下载(https://redis.io/download)时,一定要了解下官网提及的版本规则及更新信息

  • Redis 使用标准版本标记进行版本控制:major.minor.patchlevel。偶数的版本号表示稳定的版本, 例如 1.2,2.0,2.2,2.4,2.6,2.8,奇数的版本号用来表示非标准版本,例如2.9.x是非稳定版本,它的稳定版本是3.0。
  • Redis 4.0在2017年7月以GA的形式发布,新用户应该使用Redis 5,但Redis 4是目前最成熟的版本,并将在明年更新,直到Redis 6发布。
  • Redis 5.0是Redis的第一个重大更新版本,引入了新的流数据类型与消费者组,排序集阻塞pop操作,RDB中的LFU/LRU信息,Redis -cli中的集群管理器,活跃的碎片整理V2, HyperLogLogs改进和许多其他改进,2018年10月,Redis 5作为GA发布。
  • Redis 6.0引入了SSL,新的RESP3协议,acl,客户端缓存,无磁盘副本,I/O线程,更快的RDB加载,新的模块api和更多的改进。

经过一番比较后,最终选择使用Redis 5版本!,下载地址:https://download.redis.io/releases/

Windows 安装和使用 Redis

值得注意的是,从Redis3.x开始一直到目前的Redis6.x,官网一直没有提供Windows系统的 Redis安装包,只提供了Linux或Docker的。因此,没必要折腾去寻找能在Windows安装的zip包了。

另外,关于官网为什么不提供Windows的Redis安装包,原因可能是:

  • redis是基于单线程的高性能操作,而redis需要单线程轮询,Windows和Linux的轮询机制有所不同。
  • Windows使用的是selector,而Linux使用的是epoll,从性能上来说 epoll是高于selector 的,所以redis官方推荐使用linux版本。不过,window版本的redis是民间大神或者微软修改过的,可以在网上搜到相关的安装包使用,不过最新版本是不可能和官方保持一致的。

Linux 安装和使用 Redis

使用环境

  • CentOS 7.6
  • redis-5.0.14 【暂用单机版】

安装步骤

下载安装包

去Redis官网下载Linux安装包:

image-20211205141922934

也可以通过wget直接下载到虚拟机中

$ wget https://download.redis.io/releases/redis-5.0.14.tar.gz

检查gcc环境

redis是c语言编写的, 因此下载之后还需要使用gcc(9.3+)进行编译和安装.

查看gcc版本是否在9.3以上, 如果没有则需要安装

# 查看gcc版本是否在9.3以上,centos7.6默认安装4.8.5
$ gcc -v

如果发现gcc版本低于9.3, 我们需要升级到9.3及以上,如下:

$ sudo yum -y install centos-release-scl
$ sudo yum -y install devtoolset-9-gcc devtoolset-9-gcc-c++ devtoolset-9-binutils

$ scl enable devtoolset-9 bash

需要注意的是scl命令切换gcc版本只是临时的,退出shell或重启就会恢复原系统gcc版本。如果要长期使用gcc 9.3的话:

echo "source /opt/rh/devtoolset-9/enable" >>/etc/profile

编译redis

将下载的压缩包上传到/usr/local目录下,解压编译。

解压同时进入目录进行编译:

# 解压
tar zxf redis-5.0.14.tar.gz -C ~/app
# 编译依赖 - redis 5.x 需要
cd ~/app/redis-5.0.14/deps
make hiredis jemalloc linenoise lua
# 编译
cd ~/app/redis-5.0.14
make MALLOC=libc
# 测试
make test

如果编译测试过程发生错误提示

"You need tcl 8.5 or newer in order to run the Redis test"

则还需要安装tcl依赖

sudo yum install tcl -y

编译后产生一个新的src目录,将里面文件cp到/usr/local/bin/

cp -rf src/redis-server /usr/local/bin/
cp -rf src/redis-cli /usr/local/bin/

进入src目录并安装Redis服务:

cd src
sudo make install

这样可以将Redis服务器和客户端命令安装到默认位置/usr/local/bin/下面
也可以在make install的时候指定一个前缀PREFIX,指定一个自定义的安装位置

cd src
sudo make install PREFIX=~/app/redis-5.0.14/

至此,Redis安装完毕。

启动Redis

前台启动

$ redis-server

启动效果:

image-20211204143602980

PS:这种启动方式如果关闭终端,redis就直接退出了,所以我们需要下面的后台启动!

后台启动

  1. 修改 redis.conf 文件

    1. daemonize no 改为 daemonize yes

    2. 注释掉 # bind 127.0.0.1

    3. 修改 protected-mode yes 改为 protected-mode no

    4. 如果需要设置密码添加 requirepass niit1234

    5. 修改后的部分示例如下:

      # By default protected mode is enabled. You should disable it only if
      # you are sure you want clients from other hosts to connect to Redis
      # even if no authentication is configured, nor a specific set of interfaces
      # are explicitly listed using the "bind" directive.
      protected-mode no
      
      # Accept connections on the specified port, default is 6379 (IANA #815344).
      # If port 0 is specified Redis will not listen on a TCP socket.
      port 6379
      
      # By default Redis does not run as a daemon. Use 'yes' if you need it.
      daemonize yes
      
      # IMPORTANT NOTE: starting with Redis 6 "requirepass" is just a compatibility
      # layer on top of the new ACL system. The option effect will be just setting
      # the password for the default user. Clients will still authenticate using
      # AUTH  as usually, or more explicitly with AUTH default 
      # if they follow the new protocol: both will work.
      #
      # requirepass foobared
      requirepass niit1234
  2. 启动和停止后台服务

    ## 启动服务
    [redis-5.0.14]$ redis-server redis.conf
  3. 通过命令查看进程和端口(即启动时显示的PID和PORT)

    ## 查看进程
    [redis-5.0.14]$ ps -ef | grep redis
    ## 查看端口
    [redis-5.0.14]$ netstat -anpt | grep redis
  4. 停止后台服务

    ## 方法1. 如果知道Redis服务的进程ID可以使用Kill命令停止
    kill -9 <进程号>
    
    ## 方法2. 通过Redis Cli命令行客户端停止服务
    ## 如设置密码需要先认证
    [redis-5.0.14]$ bin/redis-cli
    127.0.0.1:6379> auth "niit1234"    # 认证密码
    OK
    127.0.0.1:6379> shutdown

作为系统服务

将配置文件复制到/etc/redis下

$ sudo mkdir /etc/redis
$ sudo cp redis.conf /etc/redis/6379.conf

安装服务

$ cd utils/
Welcome to the redis service installer
This script will help you easily set up a running redis server

Please select the redis port for this instance: [6379]
Selecting default: 6379
Please select the redis config file name [/etc/redis/6379.conf]
Selected default - /etc/redis/6379.conf
Please select the redis log file name [/var/log/redis_6379.log]
Selected default - /var/log/redis_6379.log
Please select the data directory for this instance [/var/lib/redis/6379]
Selected default - /var/lib/redis/6379
Please select the redis executable path [] /usr/local/bin/redis-server
Selected config:
Port           : 6379                           # 默认端口号
Config file    : /etc/redis/6379.conf           # redis服务使用的配置文件
Log file       : /var/log/redis_6379.log        # redis服务器日志
Data dir       : /var/lib/redis/6379            # redis 数据存储目录
Executable     : /usr/local/bin/redis-server    # redis服务命令所在位置
Cli Executable : /usr/local/bin/redis-cli    # redis客户端命令所在位置
Is this ok? Then press ENTER to go on or Ctrl-C to abort.
Copied /tmp/6379.conf => /etc/init.d/redis_6379
Installing service...
Successfully added to chkconfig!
Successfully added to runlevels 345!
Starting Redis server...
Installation successful!

安装完毕后使用chkconfig查看已经安装的服务, 并且此时redis服务已经在运行了.

[hadoop@hadoop000 utils]$ chkconfig

注:该输出结果只显示 SysV 服务,并不包含
原生 systemd 服务。SysV 配置数据
可能被原生 systemd 配置覆盖。

      要列出 systemd 服务,请执行 'systemctl list-unit-files'。
      查看在具体 target 启用的服务请执行
      'systemctl list-dependencies [target]'。

netconsole      0:关    1:关    2:关    3:关    4:关    5:关    6:关
network         0:关    1:关    2:开    3:开    4:开    5:开    6:关
redis_6379      0:关    1:关    2:开    3:开    4:开    5:开    6:关

可以看到, 新安装的服务名称为redis_6379, 并且已经配置了开机自动启动服务

也可以使用命令$ sudo chkconfig redis_6379 off关闭开机自动启动服务.

接下来就可以使用如下命令管理Redis系统服务了.

查看服务状态

$ service redis_6379 status
Redis is running (107335)

关闭服务

$ service redis_6379 stop
Stopping ...
(error) NOAUTH Authentication required.

这里无法关闭服务的原因是我们之前在redis.conf配置文件中设置了requirepasswd
所以解决办法

  1. 取消密码
  2. 修改服务启动文件

    $ sudo vi /etc/init.d/redis_6379
    
    # 修改如下
    36      stop)
    37          if [ ! -f $PIDFILE ]
    38          then
    39              echo "$PIDFILE does not exist, process is not running"
    40          else
    41              PID=$(cat $PIDFILE)
    42              echo "Stopping ..."
    43              # $CLIEXEC -p $REDISPORT shutdown
    44              $CLIEXEC -a "niit1234" -p $REDISPORT shutdown
    45              while [ -x /proc/${PID} ]
    46              do
    47                  echo "Waiting for Redis to shutdown ..."
    48                  sleep 1
    49              done
    50              echo "Redis stopped"
    51          fi
    52          ;;
    

    修改完成后再次关闭服务就可以成功了

    $ service redis_6379 stop
    Stopping ...
    Warning: Using a password with '-a' or '-u' option on the command line interface may not be safe.
    Redis stopped

    启动服务

    $ sudo service redis_6379 start
    Starting Redis server...

使用客户端连接服务

$ redis-cli
127.0.0.1:6379> auth niit1234
OK

卸载Redis

停服务、删文件即可!

#查看进程
ps aux |grep redis
#杀掉进程
kill -9 <进程号>
#查看相关文件
find / -name "redis*"
# rm -rf 删除redis相关文件, 例如:
sudo rm -rf /etc/redis
sudo rm -rf /var/lib/redis
sudo rm -rf /etc/rc.d/init.d/redis_6379
sudo rm -rf /var/log/redis_6379.log
sudo rm -rf /usr/local/bin/redis-*
sudo rm -rf /home/hadoop/app/redis-5.0.14

其他可能出现的问题及解决办法

执行service redis_6379 start命令时,出现提示:

/var/run/redis_6379.pid exists, process is already running or crashed

删除这个pid即可

rm -rf /var/run/redis_6379.pid

Redis性能测试

模拟N个客户端同时发出M个请求:

  • 通过redis-benchmark命令,测试结果如下:(每秒请求数)
$ ./src/redis-benchmark -n 10000 -q
PING_INLINE: 18115.94 requests per second
PING_BULK: 22988.51 requests per second
SET: 36496.35 requests per second
GET: 22883.29 requests per second
INCR: 24570.02 requests per second
LPUSH: 34722.22 requests per second
RPUSH: 20202.02 requests per second
LPOP: 24330.90 requests per second
RPOP: 30120.48 requests per second
SADD: 25252.53 requests per second
HSET: 28571.43 requests per second
SPOP: 35842.29 requests per second
LPUSH (needed to benchmark LRANGE): 15673.98 requests per second
LRANGE_100 (first 100 elements): 10405.83 requests per second
LRANGE_300 (first 300 elements): 9442.87 requests per second
LRANGE_500 (first 450 elements): 7374.63 requests per second
LRANGE_600 (first 600 elements): 5827.51 requests per second
MSET (10 keys): 31055.90 requests per second

使用Redis客户端

使用redi-cli客户端通过命令操作redis,这里先热身一下:

redis-5.0.8]$ ./src/redis-cli
127.0.0.1:6379> set msg helloworld
OK
127.0.0.1:6379> get msg
"helloworld"
127.0.0.1:6379> set cnt 100
OK
127.0.0.1:6379> incr cnt
(integer) 101
127.0.0.1:6379> incrby cnt 10
(integer) 111
127.0.0.1:6379> mset apple 6.82 orange 3.5 banana 9.9
OK
127.0.0.1:6379> mget apple orange banana
1) "6.82"
2) "3.5"
3) "9.9"
127.0.0.1:6379> rpush list0 java
(integer) 1
127.0.0.1:6379> rpush list0 python
(integer) 2
127.0.0.1:6379> rpush list0 go
(integer) 3
127.0.0.1:6379> lrange list0 0 -1
1) "java"
2) "python"
3) "go"
127.0.0.1:6379>

用可视化工具管理 Redis

名称: AnotherRedisDesktopManager

前身是一个工具叫做 RedisDesktopManager, 由于不再更新, 因此有人又制作了另外一款工具起名为AnotherRedisDesktopManager

下载:

GITHUB地址

exe可执行文件下载链接

使用

  1. 创建连接,输入HOST、端口(默认6379)密码(AUTH),连接名称(Name)点击OK,成功!

    image-20201214235231573

连接成功后可以使用AnotherRedisDesktopManager内置的Redis客户端工具与服务器进行交互:

image-20211205185535140

可视化界面可以方便查看和搜索那些已经存储的键值对.

image-20201214235712329

如果要清空所有缓存的数据, 可以点击flush DB选项

image-20211205185659993

当然还有很多其他功能, 这个软件和其他的数据库管理软件类似, 很快就可以上手了.

Views: 248