32、Redis

1、Nosql 概述

1.1、为什么使用Nosql

1.1.1、单机Mysql时代

  • 90年代,一个网站的访问量一般不会太大,更多的是使用静态网页,单个数据库完全够用,服务器没有太大的压力。
  • 随着用户增多,网站出现以下问题:
    1. 数据量增加到一定程度,单机数据库就放不下了。
    2. 数据的索引(B+ Tree),一个机器内存也存放不下。
    3. 访问量变大后(读写混合),一台服务器承受不住。

1.1.2、Memcached(缓存) + Mysql + 垂直拆分(读写分离)

  • 网站80%的情况都是在读,每次都要去查询数据库的话就十分麻烦!因此,我们希望减轻数据库的压力,可以使用缓存来保证效率!

  • 优化过程经历了以下几个过程:
    1. 优化数据库的数据结构和索引(难度大)
    2. 文件缓存,通过IO流获取比每次都访问数据库效率略高,但是流量爆炸式增长时候,IO流也承受不了
    3. MemCache,当时最热门的技术,通过在数据库和数据库访问层之间加上一层缓存,第一次访问时查询数据库,将结果保存到缓存,后续的查询先检查缓存,若有直接拿去使用,效率显著提升。

1.1.3、分库分表 + 水平拆分 + Mysql集群

  • 技术和业务在发展的同时,对人的要求也越来越高了
  • 本质:数据库(读、写)
  • 此时,数据库的引擎也发生了变化:
    • 之前是 MyISAM :表锁,查询数据锁住整个表,影响效率。
    • 后来是 InnoDB :行锁,查询数据锁住对应的那一行。
  • 用户持续增多,少量数据库也满足不了需求了,就需要使用 MySQL 集群。每一个集群都具有 M(master)和 S(slave)。把之前整个数据库进行拆分,把不同功能的数据进行拆分,减轻单个群的压力。

1.1.4、如今最近的年代

  • 如今信息量井喷式增长,各种各样的数据出现(用户定位数据,图片数据,音乐数据等),大数据的背景下Mysql等关系型数据库(RDBMS)无法满足大量数据要求。因此,出现了很多新型的非关系型数据,Nosql数据库就能轻松解决这些问题,专门存储大型文件、图片、博客。目前一个基本的互联网项目:

  • 为什么要用NoSQL?

    • 用户的个人信息,社交网络,地理位置,用户自己产生的数据,用户日志等等爆发式增长!
    • 这时候就需要使用NoSQL数据库的,Nosql可以很好地处理以上情况!

1.2、什么是Nosql

  • NoSQL = Not Only SQL(不仅仅是SQL)= Not Only Structured Query Language
  • 关系型数据库:列+行,同一个表下数据的结构是一样的。
  • 非关系型数据库:数据存储没有固定的格式,并且可以进行横向扩展。
  • NoSQL泛指非关系型数据库,随着web2.0互联网的诞生,传统的关系型数据库很难对付web 2.0时代!尤其是超大规模的高并发的社区,暴露出来很多难以克服的问题,NoSQL在当今大数据环境下发展的十分迅速,Redis是发展最快的。
  • 很多的数据类型用户的个人信息、社交网络、地理位置,这些数据类型的存储不需要一个固定的格式!不需要多余的操作就可以横向扩展的!Map<String,Object> 使用键值对来控制!

1.2.1、Nosql特点

  1. 方便扩展(数据之间没有关系,很好扩展!)

  2. 大数据量高性能(Redis一秒可以写8万次,读11万次,NoSQL的缓存记录级,是一种细粒度的缓存,性能会比较高!)

  3. 数据类型是多样型的!(不需要事先设计数据库,随取随用)

  4. 传统的 RDBMS 和 NoSQL:

    RDBMS(关系型数据库)
    - 结构化组织
    - SQL
    - 数据和关系都存在单独的表中 row col
    - 操作,数据定义语言
    - 严格的一致性
    - 基础的事务
    - ...
    
    NoSQL(非关系型数据库)
    - 不仅仅是数据
    - 没有固定的查询语言
    - 键值对存储,列存储,文档存储,图形数据库(社交关系)
    - 最终一致性
    - CAP定理和BASE理论
    - 高性能,高可用,高可扩展
    - ...
    
  5. 了解:3V + 3高

    • 大数据时代的3V :主要是描述问题
      1. 海量Velume
      2. 多样Variety
      3. 实时Velocity
    • 大数据时代的3高 : 主要是对程序的要求
      1. 高并发

      2. 高可扩展

      3. 高性能

  6. 真正在公司中的实践:NoSQL + RDBMS 一起使用才是最强的。

1.2.2、阿里巴巴演进分析

  • 推荐阅读:阿里云的这群疯子(https://yq.aliyun.com/articles/653511

  • 阿里巴巴架构发展历程

  • 数据层架构

    # 商品信息:名称、价格、商家信息
    - 一般存放在关系型数据库:MySQL,阿里巴巴使用的MySQL都是经过内部改动的(王坚)
    
    # 商品描述、评论(文字居多)
    - 文档型数据库:MongoDB
    
    # 图片
    - 分布式文件系统 FastDFS
    - 淘宝:TFS
    - Google: GFS
    - Hadoop: HDFS
    - 阿里云: oss
    
    # 商品关键字,用于搜索
    - 搜索引擎:solr elasticsearch
    - 阿里:Isearch(多隆)
    
    # 商品热门的波段信息
    - 内存数据库:Redis Tair Memcache
    
    # 商品交易,外部支付接口
    - 第三方应用
    

1.2.3、Nosql的四大分类

KV键值对

  • 新浪:Redis
  • 美团:Redis + Tair
  • 阿里、百度:Redis + Memcache

文档型数据库(bson数据格式):

  • MongoDB(掌握)
    • 基于分布式文件存储的数据库。C++编写,用于处理大量文档。
      • MongoDB是介于RDBMS和NoSQL之间的中间产品。MongoDB是非关系型数据库中功能最丰富的,NoSQL中最像关系型数据库的数据库。
  • ConthDB

列存储数据库

  • HBase(大数据必学)
  • 分布式文件系统

图关系数据库

  • 用于广告推荐,社交网络

  • Neo4j、InfoGrid

四者对比

分类Examples举例典型应用场景数据模型优点缺点
键值对(key-value)Tokyo Cabinet/Tyrant, Redis, Voldemort, Oracle BDB内容缓存,主要用于处理大量数据的高访问负载,也用于一些日志系统等等。Key 指向 Value 的键值对,通常用hash table来实现查找速度快数据无结构化,通常只被当作字符串或者二进制数据
列存储数据库Cassandra, HBase, Riak分布式的文件系统以列簇式存储,将同一列数据存在一起查找速度快,可扩展性强,更容易进行分布式扩展功能相对局限
文档型数据库CouchDB, MongoDbWeb应用(与Key-Value类似,Value是结构化的,不同的是数据库能够了解Value的内容)Key-Value对应的键值对,Value为结构化数据数据结构要求不严格,表结构可变,不需要像关系型数据库一样需要预先定义表结构查询性能不高,而且缺乏统一的查询语法。
图形(Graph)数据库Neo4J, InfoGrid, Infinite Graph社交网络,推荐系统等。专注于构建关系图谱图结构利用图结构相关算法。比如最短路径寻址,N度关系查找等很多时候需要对整个图做计算才能得出需要的信息,而且这种结构不太好做分布式的集群

2、Redis 入门

2.1、概述

2.1.1、Redis是什么

  • Redis(Remote Dictionary Server ),即远程字典服务。
  • 是一个开源的使用ANSI C语言编写、支持网络、可基于内存亦可持久化的日志型、Key-Value数据库,并提供多种语言的API。
  • 免费和开源!是当下最热[门]的NoSQL技术之一,也被人们称之为结构化数据库。
  • 与memcached一样,为了保证效率,数据都是缓存在内存中。区别的是redis会周期性的把更新的数据写入磁盘或者把修改操作写入追加的记录文件,并且在此基础上实现了master-slave(主从)同步。

2.1.2、Redis能干什么

  1. 内存存储、持久化,内存是断电即失的,所以需要持久化(RDB、AOF)
  2. 高效率、用于高速缓冲
  3. 发布订阅系统
  4. 地图信息分析
  5. 计时器、计数器(eg:浏览量)

2.1.3、特性

  • 多样的数据类型、持久化、集群、事务…

2.2、环境搭建

2.2.1、Linux安装

  1. 使用宝塔面板安装Redis,安装路径:/www/server/redis/

  2. 将redis的配置文件复制到程序安装目录 /usr/local/bin/myconfig

  3. redis默认不是后台启动的,需要修改配置文件!

  4. 启动redis服务,并使用redis-cli连接指定的端口号测试(Redis的默认端口6379)

    [root src]# ./redis-server &
    [root src]# ping
    127.0.0.1:6379> ping
    

  5. 查看redis服务是否启动,关闭Redis服务,再次查看进程是否存在

    [root src]# ps -ef|grep redis
    [root src]# redis-cli
    127.0.0.1:6379> shutdown
    127.0.0.1:6379> quit / exit
    

  6. 后续会使用单机多Redis启动集群测试!

2.2.2、测试性能

  • **redis-benchmark:**压力测试工具,Redis官方提供的性能测试工具,参数选项如下:

  • 简单测试:

    # 测试:100个并发连接 100000请求
    redis-benchmark -h 127.0.0.1 -p 6379 -c 100 -n 100000
    
  • 测试结果(片段):

    ====== SET ======                                                   
      100000 requests completed in 1.22 seconds
      100 parallel clients
      3 bytes payload
      keep alive: 1
      host configuration "save": 3600 1 300 100 60 10000
      host configuration "appendonly": no
      multi-thread: no
    
    Latency by percentile distribution:
    0.000% <= 0.199 milliseconds (cumulative count 1)
    50.000% <= 0.591 milliseconds (cumulative count 51183)
    75.000% <= 0.711 milliseconds (cumulative count 75554)
    87.500% <= 0.839 milliseconds (cumulative count 88224)
    93.750% <= 0.903 milliseconds (cumulative count 94145)
    96.875% <= 1.071 milliseconds (cumulative count 96925)
    98.438% <= 1.383 milliseconds (cumulative count 98441)
    99.219% <= 1.839 milliseconds (cumulative count 99228)
    99.609% <= 2.271 milliseconds (cumulative count 99614)
    99.805% <= 2.551 milliseconds (cumulative count 99805)
    99.902% <= 2.815 milliseconds (cumulative count 99903)
    99.951% <= 2.975 milliseconds (cumulative count 99954)
    99.976% <= 3.071 milliseconds (cumulative count 99977)
    99.988% <= 3.159 milliseconds (cumulative count 99988)
    99.994% <= 3.231 milliseconds (cumulative count 99994)
    99.997% <= 3.295 milliseconds (cumulative count 99997)
    99.998% <= 3.335 milliseconds (cumulative count 99999)
    99.999% <= 3.343 milliseconds (cumulative count 100000)
    100.000% <= 3.343 milliseconds (cumulative count 100000)
    
    Cumulative distribution of latencies:
    0.000% <= 0.103 milliseconds (cumulative count 0)
    0.002% <= 0.207 milliseconds (cumulative count 2)
    0.035% <= 0.303 milliseconds (cumulative count 35)
    0.227% <= 0.407 milliseconds (cumulative count 227)
    7.376% <= 0.503 milliseconds (cumulative count 7376)
    57.797% <= 0.607 milliseconds (cumulative count 57797)
    74.875% <= 0.703 milliseconds (cumulative count 74875)
    84.250% <= 0.807 milliseconds (cumulative count 84250)
    94.145% <= 0.903 milliseconds (cumulative count 94145)
    96.346% <= 1.007 milliseconds (cumulative count 96346)
    97.140% <= 1.103 milliseconds (cumulative count 97140)
    97.705% <= 1.207 milliseconds (cumulative count 97705)
    98.150% <= 1.303 milliseconds (cumulative count 98150)
    98.507% <= 1.407 milliseconds (cumulative count 98507)
    98.708% <= 1.503 milliseconds (cumulative count 98708)
    98.891% <= 1.607 milliseconds (cumulative count 98891)
    99.026% <= 1.703 milliseconds (cumulative count 99026)
    99.178% <= 1.807 milliseconds (cumulative count 99178)
    99.303% <= 1.903 milliseconds (cumulative count 99303)
    99.396% <= 2.007 milliseconds (cumulative count 99396)
    99.486% <= 2.103 milliseconds (cumulative count 99486)
    99.982% <= 3.103 milliseconds (cumulative count 99982)
    100.000% <= 4.103 milliseconds (cumulative count 100000)
    
    Summary:
      throughput summary: 81833.06 requests per second
      latency summary (msec):
              avg       min       p50       p95       p99       max
            0.658     0.192     0.591     0.927     1.687     3.343
    

2.3、基础知识

  1. redis默认有16个数据库,默认使用的第0个;16个数据库为:DB 0 ~ DB 15,默认使用DB 0 ,可以使用 select n 切换到DB n。

    [root@VM-4-12-centos ~]# cd /www/server/redis/src
    [root@VM-4-12-centos src]# ./redis-cli
    127.0.0.1:6379> config get databases  # 命令行查看数据库数量databases
    1) "databases"
    2) "16"
    127.0.0.1:6379> select 6  # 切换数据库 DB6
    OK
    127.0.0.1:6379[6]> dbsize  # 查看当前数据库的大小,size与key数量相关
    (integer) 0
    127.0.0.1:6379[6]> set name cwlin
    OK
    127.0.0.1:6379[6]> dbsize
    (integer) 1
    127.0.0.1:6379[6]> select 1  # 不同数据库之间数据是不能互通的,并且dbsize 是根据库中key的个数
    OK
    127.0.0.1:6379[1]> get name  # db1中并不能获取db6中的键值对
    (nil)
    127.0.0.1:6379[1]> dbsize
    (integer) 0
    127.0.0.1:6379[1]> select 6
    OK
    127.0.0.1:6379[6]> get name
    "cwlin"
    127.0.0.1:6379[6]> dbsize
    (integer) 1
    
    127.0.0.1:6379[6]> keys *  # 查看当前数据库中所有的key
    1) "name"
    127.0.0.1:6379[6]> flushdb  # 清空当前数据库中的键值对
    OK
    127.0.0.1:6379[6]> flushall  # 清空所有数据库的键值对
    OK
    
  2. Redis是单线程的,Redis是基于内存操作的。

    • Redis 是基于内存操作的,CPU 不是 Redis 的性能瓶颈,而是机器的内存和网络带宽。
    • Redis 基于C语言实现的,官方数据显示,它的QPS(每秒请求数)达到10W+,完全不比同样使用key-value的MemCache差。
  3. Redis为什么单线程速度还这么快,性能这么高呢?

    • 误区1:高性能的服务器一定是多线程的?
    • 误区2:多线程(CPU上下文会切换!)一定比单线程效率高?
    • 核心:Redis 将所有的数据放在内存中,因此使用单线程操作效率就是最高的,而多线程存在CPU上下文会切换,这是耗时的操作!对于内存系统来说,如果没有上下文切换效率就是最高的,多次读写都是在一个CPU上的,在内存存储数据情况下,单线程就是最佳的方案。

3、Redis 数据类型

3.1、五种常见数据类型

3.1.1、Redis-key

  • 在redis中无论什么数据类型,在数据库中都是以key-value形式保存,通过进行对Redis-key的操作,来完成对数据库中数据的操作。

  • 常用命令如下:

    • exists key:判断键是否存在
    • move key db:将键值对移动到指定数据库
    • del key:删除键值对
    • expire key second:设置键值对的过期时间
    • ttl key: 查看key的过期剩余时间
    • type key:查看value的数据类型
  • Linux 操作:

    127.0.0.1:6379> flushall  # 清空所有键值对
    OK
    127.0.0.1:6379> set name cwlin
    OK
    127.0.0.1:6379> set age 24
    OK 
    127.0.0.1:6379> exists name  # 判断键是否存在
    (integer) 1  # 存在
    127.0.0.1:6379> exists gender
    (integer) 0  # 不存在
    127.0.0.1:6379> move name 1  # 将键值对移动到指定数据库 DB1
    (integer) 1
    127.0.0.1:6379> keys *
    1) "age"
    127.0.0.1:6379> expire age 10  # 设置键值对的过期时间
    (integer) 1  # 设置成功,开始计数
    127.0.0.1:6379> keys *
    1) "age"
    127.0.0.1:6379> ttl age
    (integer) 5
    127.0.0.1:6379> keys *  # 过期的key会被自动delete
    (empty array)
    127.0.0.1:6379> ttl age  # 查看key的过期剩余时间
    (integer) -2 # -2表示key过期,-1表示key未设置过期时间
    127.0.0.1:6379> select 1
    OK
    127.0.0.1:6379[1]> keys *
    1) "name"
    127.0.0.1:6379[1]> del name  # 删除键值对
    (integer) 1  # 删除个数
    
    127.0.0.1:6379> type name # 查看value的数据类型
    string
    127.0.0.1:6379> type age
    string
    
  • 关于TTL命令:Redis的key,通过TTL命令返回key的过期时间,一般来说有3种:

    1. 当前key没有设置过期时间,所以会返回-1;
    2. 当前key有设置过期时间,而且key已经过期,所以会返回-2;
    3. 当前key有设置过期时间,且key还没有过期,故会返回key的正常剩余时间。
  • 关于重命名RENAMERENAMENX

    • RENAME key newkey:修改 key 的名称
    • RENAMENX key newkey:仅当 newkey 不存在时,将 key 改名为 newkey 。
  • 更多命令详见官网:

3.1.2、String(字符串)

  • 常用命令:
命令描述示例
APPEND key value向指定的key的value后追加字符串127.0.0.1:6379> set msg hello OK 127.0.0.1:6379> append msg " world" (integer) 11 127.0.0.1:6379> get msg “hello world”
DECR/INCR key将指定key的value数值进行+1/-1(仅对于数字)127.0.0.1:6379> set age 20 OK 127.0.0.1:6379> incr age (integer) 21 127.0.0.1:6379> decr age (integer) 20
INCRBY/DECRBY key n按指定的步长对数值进行加减127.0.0.1:6379> INCRBY age 5 (integer) 25 127.0.0.1:6379> DECRBY age 10 (integer) 15
INCRBYFLOAT key n为数值加上浮点型数值127.0.0.1:6379> INCRBYFLOAT age 5.2 “20.2”
STRLEN key获取key保存值的字符串长度127.0.0.1:6379> get msg “hello world” 127.0.0.1:6379> STRLEN msg (integer) 11
GETRANGE key start end按起止位置获取字符串(闭区间,起止位置都取)127.0.0.1:6379> get msg “hello world” 127.0.0.1:6379> GETRANGE msg 3 9 “lo worl”
SETRANGE key offset value用指定的value 替换key中 offset开始的值127.0.0.1:6379> SETRANGE msg 2 hello (integer) 7 127.0.0.1:6379> get msg “tehello”
GETSET key value将给定 key 的值设为 value ,并返回 key 的旧值(old value)。127.0.0.1:6379> GETSET msg test “hello world”
SETNX key value仅当key不存在时进行set127.0.0.1:6379> SETNX msg test (integer) 0 127.0.0.1:6379> SETNX name sakura (integer) 1
SETEX key seconds valueset 键值对并设置过期时间127.0.0.1:6379> setex name 10 root OK 127.0.0.1:6379> get name (nil)
MSET key1 value1 [key2 value2..]批量set键值对127.0.0.1:6379> MSET k1 v1 k2 v2 k3 v3 OK
MSETNX key1 value1 [key2 value2..]批量设置键值对,仅当参数中所有的key都不存在时执行127.0.0.1:6379> MSETNX k1 v1 k4 v4 (integer) 0
MGET key1 [key2..]批量获取多个key保存的值127.0.0.1:6379> MGET k1 k2 k3 1) “v1” 2) “v2” 3) “v3”
PSETEX key milliseconds value和 SETEX 命令相似,但它以毫秒为单位设置 key 的生存时间,
getset key value如果不存在值,则返回nil,如果存在值,获取原来的值,并设置新的值
  • APPEND key value: 向指定的key的value后追加字符串

  • STRLEN key: 获取key保存值的字符串长度

    127.0.0.1:6379> set key value
    OK
    127.0.0.1:6379> get key
    "value"
    127.0.0.1:6379> append key xixixi
    (integer) 11
    127.0.0.1:6379> get key
    "valuexixixi"
    127.0.0.1:6379> strlen key
    (integer) 11
    
  • DECR/INCR key: 将指定key的value数值进行+1/-1(仅对于数字)

  • INCRBY/DECRBY key n: 按指定的步长对数值进行加减

  • INCRBYFLOAT key n: 为数值加上浮点型数值

    127.0.0.1:6379> set views 0
    OK
    127.0.0.1:6379> get views
    "0"
    127.0.0.1:6379> incr views
    (integer) 1
    127.0.0.1:6379> incr views
    (integer) 2
    127.0.0.1:6379> get views
    "2"
    127.0.0.1:6379> decr views
    (integer) 1
    127.0.0.1:6379> decr views
    (integer) 0
    127.0.0.1:6379> get views
    "0"
    127.0.0.1:6379> incrby views 9
    (integer) 9
    127.0.0.1:6379> incrby views 9
    (integer) 18
    127.0.0.1:6379> decrby views 6
    (integer) 12
    127.0.0.1:6379> decrby views 6
    (integer) 6
    127.0.0.1:6379> incrbyfloat views 5.2 
    “11.2”
    
  • GETRANGE key start end: 按起止位置获取字符串(闭区间,起止位置都取)

  • SETRANGE key offset value:用指定的value 替换key中 offset开始的值

    127.0.0.1:6379> set msg hello,world
    OK
    127.0.0.1:6379> getrange msg 0 3
    "hell"
    127.0.0.1:6379> getrange msg 0 -1
    "hello,world"
    127.0.0.1:6379> set msg2 abcde
    OK
    127.0.0.1:6379> get msg2
    "abcde"
    127.0.0.1:6379> setrange msg2 2 xx
    (integer) 5
    127.0.0.1:6379> get msg2
    "abxxe"
    
  • SETEX key seconds value: set 键值对并设置过期时间

  • SETNX key value: 仅当key不存在时进行set

  • PSETEX key milliseconds value: 和 SETEX 命令相似,但它以毫秒为单位设置 key 的生存时间

    127.0.0.1:6379> setex age 20 25  # 20秒后过期
    OK
    127.0.0.1:6379> ttl age
    (integer) 17
    127.0.0.1:6379> get age
    "25"
    127.0.0.1:6379> setnx myage 24
    (integer) 1
    127.0.0.1:6379> keys *
    1) "msg2"
    2) "myage"
    3) "msg"
    127.0.0.1:6379> setnx myage 30
    (integer) 0
    127.0.0.1:6379> get myage
    "24"
    127.0.0.1:6379> psetex age 5000 25
    OK
    127.0.0.1:6379> ttl age
    (integer) 4
    127.0.0.1:6379> ttl age
    (integer) -2
    
  • MSET key1 value1 [key2 value2..]: 批量set键值对

  • MGET key1 [key2..]: 批量获取多个key保存的值

  • MSETNX key1 value1 [key2 value2..]: 批量设置键值对,仅当参数中所有的key都不存在时执行

    127.0.0.1:6379> MSET k1 v1 k2 v2 k3 v3
    OK
    127.0.0.1:6379> MGET k1 k2 k3 
    1) "v1"
    2) "v2"
    3) "v3"
    127.0.0.1:6379> MSETNX k1 v1 k4 v4
    (integer) 0  # 执行失败,因为MSETNX是原子性操作,要么一起成功,要么一起失败
    127.0.0.1:6379> get k4
    (nil)
    
  • GETSET key value: 将给定 key 的值设为 value ,并返回 key 的旧值(old value)

    127.0.0.1:6379> set name cwlin
    OK
    127.0.0.1:6379> getset name lcw
    "cwlin"
    127.0.0.1:6379> get name
    "lcw"
    127.0.0.1:6379> getset nickname chwlyn  # 如果不存在旧值,则返回nil
    (nil)
    127.0.0.1:6379> get nickname
    "chwlyn"
    
  • 存入一个 user 对象

    • 方式一:使用 JSON 字符串作为值存入
    127.0.0.1:6379> set user:1 {name:cwlin,age:18}
    OK
    127.0.0.1:6379> get user:1
    "{name:cwlin,age:18}"
    
    • 方式二:把对象的名字和属性名结合,整体作为键,属性的值作为键的值
    127.0.0.1:6379> mset user:2:name lcw user:2:age 24
    OK
    127.0.0.1:6379> mget user:2:name user:2:age
    1) "lcw"
    2) "24"
    
  • String类似的使用场景:(value除了是字符串还可以是数字)

    • 计数器
    • 统计多单位的数量:uid: 123666 follow: 0
    • 粉丝数
    • 对象存储缓存

3.1.3、List(列表)

  • Redis列表是简单的字符串列表,按照插入顺序排序。你可以添加一个元素到列表的头部(左边)或者尾部(右边)

    • 一个列表最多可以包含 2^32 - 1 个元素 (4294967295,每个列表超过40亿个元素)。
    • 在 Redis 中可以利用 List 经过规则定义实现 栈、队列、双端队列、阻塞队列
  • 所有的 List 命令都是 L / R 开头的,List是可以进行双端操作的,所以命令分为LXXX和RXXX两类,有时候L也表示List,例如LLEN

    • LPUSH/RPUSH key value1[value2..]: 从左边/右边向列表中PUSH值(一个或者多个)。
    • LRANGE key start end: 获取list 起止元素==(索引从左往右 递增)==
    • LPUSHX/RPUSHX key value: 向已存在的列名中push值(一个或者多个)
    • LINSERT key BEFORE|AFTER pivot value: 在指定列表元素的前/后 插入value
    • LLEN key: 查看列表长度
    • LINDEX key index: 通过索引获取列表元素
    • LSET key index value: 通过索引为元素设值
    • LPOP/RPOP key: 从最左边/最右边移除值 并返回
    • RPOPLPUSH source destination: 将列表的尾部(右)最后一个值弹出,并返回,然后加到另一个列表的头部
    • LTRIM key start end: 通过下标截取指定范围内的列表
    • LREM key count value: List中是允许value重复的,count > 0:从头部开始搜索,然后删除指定的value至多删除count个;count < 0:从尾部开始搜索,…;count = 0:删除列表中所有的指定value。
    • BLPOP/BRPOP key1[key2] timeout: 移出并获取列表的第一个/最后一个元素, 如果列表没有元素会阻塞列表直到等待超时或发现可弹出元素为止。
    • BRPOPLPUSH source destination timeout: 和RPOPLPUSH功能相同,如果列表没有元素会阻塞列表直到等待超时或发现可弹出元素为止。
  • Linux 操作实例:

    ---------------------------LPUSH---RPUSH---LRANGE--------------------------------
    
    127.0.0.1:6379> LPUSH mylist k1  # LPUSH mylist => {1}
    (integer) 1
    127.0.0.1:6379> LPUSH mylist k2  # LPUSH mylist => {2,1}
    (integer) 2
    127.0.0.1:6379> RPUSH mylist k3  # RPUSH mylist => {2,1,3}
    (integer) 3
    127.0.0.1:6379> get mylist  # 普通的get是无法获取list值的
    (error) WRONGTYPE Operation against a key holding the wrong kind of value
    127.0.0.1:6379> LRANGE mylist 0 4  # LRANGE获取起止位置范围内的元素
    1) "k2"
    2) "k1"
    3) "k3"
    127.0.0.1:6379> LRANGE mylist 0 2
    1) "k2"
    2) "k1"
    3) "k3"
    127.0.0.1:6379> LRANGE mylist 0 1
    1) "k2"
    2) "k1"
    127.0.0.1:6379> LRANGE mylist 0 -1  # 获取全部元素
    1) "k2"
    2) "k1"
    3) "k3"
    
    ---------------------------LPUSHX---RPUSHX-----------------------------------
    
    127.0.0.1:6379> LPUSHX list v1  # list不存在,LPUSHX失败
    (integer) 0
    127.0.0.1:6379> LPUSHX list v1 v2  
    (integer) 0
    127.0.0.1:6379> LPUSHX mylist k4 k5  # 向mylist的左边 PUSH k4 k5
    (integer) 5
    127.0.0.1:6379> LRANGE mylist 0 -1
    1) "k5"
    2) "k4"
    3) "k2"
    4) "k1"
    5) "k3"
    
    ---------------------------LINSERT---LLEN---LINDEX---LSET----------------------------
    
    127.0.0.1:6379> LINSERT mylist after k2 ins_key1  # 在k2元素后,插入ins_key1
    (integer) 6
    127.0.0.1:6379> LRANGE mylist 0 -1
    1) "k5"
    2) "k4"
    3) "k2"
    4) "ins_key1"
    5) "k1"
    6) "k3"
    127.0.0.1:6379> LLEN mylist  # 查看mylist的长度
    (integer) 6
    127.0.0.1:6379> LINDEX mylist 3  # 获取下标为3的元素
    "ins_key1"
    127.0.0.1:6379> LINDEX mylist 0
    "k5"
    127.0.0.1:6379> LSET mylist 3 k6  # 将下标3的元素set值为k6
    OK
    127.0.0.1:6379> LRANGE mylist 0 -1
    1) "k5"
    2) "k4"
    3) "k2"
    4) "k6"
    5) "k1"
    6) "k3"
    
    ---------------------------LPOP---RPOP--------------------------
    
    127.0.0.1:6379> LPOP mylist  # 左侧(头部)弹出
    "k5"
    127.0.0.1:6379> RPOP mylist  # 右侧(尾部)弹出
    "k3"
    
    ---------------------------RPOPLPUSH--------------------------
    
    127.0.0.1:6379> LRANGE mylist 0 -1
    1) "k4"
    2) "k2"
    3) "k6"
    4) "k1"
    127.0.0.1:6379> RPOPLPUSH mylist newlist  # 将mylist的最后一个值(k1)弹出,加入到newlist的头部
    "k1"
    127.0.0.1:6379> LRANGE newlist 0 -1
    1) "k1"
    127.0.0.1:6379> LRANGE mylist 0 -1
    1) "k4"
    2) "k2"
    3) "k6"
    
    ---------------------------LTRIM--------------------------
    
    127.0.0.1:6379> LTRIM mylist 0 1  # 截取mylist中的 0~1 部分
    OK
    127.0.0.1:6379> LRANGE mylist 0 -1
    1) "k4"
    2) "k2"
    
    # 初始 mylist: k2,k2,k2,k2,k2,k2,k4,k2,k2,k2,k2
    ---------------------------LREM--------------------------
    
    127.0.0.1:6379> LREM mylist 3 k2  # 从头部开始搜索,至多删除3个 k2
    (integer) 3
    # 删除后:mylist: k2,k2,k2,k4,k2,k2,k2,k2
    
    127.0.0.1:6379> LREM mylist -2 k2  #从尾部开始搜索,至多删除2个 k2
    (integer) 2
    # 删除后:mylist: k2,k2,k2,k4,k2,k2
    
  • 阻塞队列的应用:

    • BLPOP/BRPOP key1[key2] timout: 移出并获取列表的第一个/最后一个元素, 如果列表没有元素会阻塞列表直到等待超时或发现可弹出元素为止。
    • BRPOPLPUSH source destination timeout: 和RPOPLPUSH功能相同,如果列表没有元素会阻塞列表直到等待超时或发现可弹出元素为止。
    ---------------------------BLPOP---BRPOP--------------------------
    
    127.0.0.1:6379> lpush mylist k2 k2 k2 k4 k2 k2
    (integer) 6
    127.0.0.1:6379> lpush newlist k1 k3
    (integer) 2
    127.0.0.1:6379> LRANGE mylist 0 -1
    1) "k2"
    2) "k2"
    3) "k4"
    4) "k2"
    5) "k2"
    6) "k2"
    127.0.0.1:6379> LRANGE newlist 0 -1
    1) "k3"
    2) "k1"
    127.0.0.1:6379> blpop newlist mylist 30  # 从newlist中弹出第一个值,mylist作为候选
    1) "newlist"  # 从newlist弹出
    2) "k3"
    127.0.0.1:6379> blpop newlist mylist 30
    1) "newlist"  # 从newlist弹出
    2) "k1"
    127.0.0.1:6379> blpop newlist mylist 30
    1) "mylist"  # 由于newlist空了 从mylist中弹出
    2) "k2"
    127.0.0.1:6379> blpop newlist 30
    (30.10s)  # 阻塞超时
    
    127.0.0.1:6379> blpop newlist 30
    # 阻塞等待
    127.0.0.1:6379> lpush newlist test  # 通过连接另一个客户端,向newlist中push test
    (integer) 1
    127.0.0.1:6379> blpop newlist 30  # 此时阻塞被解决
    1) "newlist"
    2) "test"
    (2.70s)
    
  • 小结:

    • list实际上是一个链表,before Node after, left, right 都可以插入值

    • 如果key不存在,则创建新的链表;如果key存在,新增内容

    • 如果移除了所有值,则为空链表,即不存在

    • 在两边插入或者改动值,效率最高!修改中间元素,效率相对较低。

  • 应用:消息排队!

    • 消息队列(LPUSH、RPOP):从左边插入(LPUSH)、从右边读取(RPOP)
    • 消息栈(LPUSH、LPOP):从左边插入(LPUSH)、从左边读取(LPOP)

3.1.4、Set(集合)

  • Redis的Set是string类型的无序集合。集合成员是唯一的,这就意味着集合中不能出现重复的数据。

    • Redis 中 集合是通过哈希表实现的,所以添加,删除,查找的复杂度都是O(1)。
    • 集合中最大的成员数为 2^32 - 1 (4294967295, 每个集合可存储40多亿个成员)。
  • Set 相关的操作都是 S 开头,常用命令如下:

    • SADD key member1[member2..]: 向集合中无序增加一个/多个成员
    • SCARD key: 获取集合的成员数
    • SMEMBERS key: 返回集合中所有的成员
    • SISMEMBER key member: 查询member元素是否是集合的成员,结果是无序的
    • SRANDMEMBER key [count]: 随机返回集合中count个成员,count缺省值为1
    • SPOP key [count]: 随机移除并返回集合中count个成员,count缺省值为1
    • SMOVE source destination member: 将source集合的成员member移动到destination集合
    • SREM key member1[member2..]: 移除集合中一个/多个成员
    • SDIFF key1[key2..]: 返回所有集合的差集(key1 - key2 - …)
    • SDIFFSTORE destination key1[key2..]: 在SDIFF的基础上,存储结果覆盖到集合中。(不能保存到其他类型key!)
    • SINTER key1 [key2..]: 返回所有集合的交集(key1 ∩ key2 ∩ …)
    • SINTERSTORE destination key1[key2..]: 在SINTER的基础上,存储结果覆盖到集合中。(不能保存到其他类型key!)
    • SUNION key1 [key2..]: 返回所有集合的并集(key1 ∪ key2 ∪ …)
    • SUNIONSTORE destination key1 [key2..]: 在SUNION的基础上,存储结果覆盖到集合中。(不能保存到其他类型key!)
    • SSCAN KEY [MATCH pattern] [COUNT count]: 在大量数据环境下,使用此命令遍历集合中元素,每次遍历count个。
  • Linux 操作实例:

    ---------------SADD--SCARD--SMEMBERS--SISMEMBER--------------------
    
    127.0.0.1:6379> SADD myset m1 m2 m3 m4 # 向myset中增加成员 m1~m4
    (integer) 4
    127.0.0.1:6379> SCARD myset # 获取集合的成员数目
    (integer) 4
    127.0.0.1:6379> smembers myset # 获取集合中所有成员
    1) "m4"
    2) "m3"
    3) "m2"
    4) "m1"
    127.0.0.1:6379> SISMEMBER myset m5 # 查询m5是否是myset的成员
    (integer) 0 # 不是,返回0
    127.0.0.1:6379> SISMEMBER myset m2
    (integer) 1 # 是,返回1
    127.0.0.1:6379> SISMEMBER myset m3
    (integer) 1
    
    ---------------------SRANDMEMBER--SPOP----------------------------------
    
    127.0.0.1:6379> SRANDMEMBER myset 3 # 随机返回3个成员
    1) "m2"
    2) "m3"
    3) "m4"
    127.0.0.1:6379> SRANDMEMBER myset # 随机返回1个成员
    "m3"
    127.0.0.1:6379> SPOP myset 2 # 随机移除并返回2个成员
    1) "m1"
    2) "m4"
    # 将set还原到{m1,m2,m3,m4}
    
    ---------------------SMOVE--SREM----------------------------------------
    
    127.0.0.1:6379> SMOVE myset newset m3 # 将myset中m3成员移动到newset集合
    (integer) 1
    127.0.0.1:6379> SMEMBERS myset
    1) "m4"
    2) "m2"
    3) "m1"
    127.0.0.1:6379> SMEMBERS newset
    1) "m3"
    127.0.0.1:6379> SREM newset m3 # 从newset中移除m3元素
    (integer) 1
    127.0.0.1:6379> SMEMBERS newset
    (empty list or set)
    
    # 下面开始是多集合操作,多集合操作中若只有一个参数默认和自身进行运算
    # setx => {m1,m2,m4,m6}, sety => {m2,m5,m6}, setz => {m1,m3,m6}
    
    -----------------------------SDIFF------------------------------------
    
    127.0.0.1:6379> SDIFF setx sety setz # 等价于 setx - sety - setz
    1) "m4"
    127.0.0.1:6379> SDIFF setx sety # setx - sety
    1) "m4"
    2) "m1"
    127.0.0.1:6379> SDIFF sety setx # sety - setx
    1) "m5"
    
    
    -------------------------SINTER---------------------------------------
    
    127.0.0.1:6379> SINTER setx sety setz # 求 setx、sety、setx 的交集
    1) "m6"
    127.0.0.1:6379> SINTER setx sety # 求setx sety 的交集
    1) "m2"
    2) "m6"
    
    -------------------------SUNION---------------------------------------
    
    127.0.0.1:6379> SUNION setx sety setz # setx sety setz 的并集
    1) "m4"
    2) "m6"
    3) "m3"
    4) "m2"
    5) "m1"
    6) "m5"
    127.0.0.1:6379> SUNION setx sety # setx sety 的并集
    1) "m4"
    2) "m6"
    3) "m2"
    4) "m1"
    5) "m5"
    
    -------------------------SSCAN----------------------------------------
    
    127.0.0.1:6379> sadd myset cwlin lcw coder_lcw chwlyn
    (integer) 4
    127.0.0.1:6379> sscan myset 0 match chw
    1) "0"
    2) (empty array)
    127.0.0.1:6379> sscan myset 0 match *lcw*
    1) "0"
    2) 1) "coder_lcw"
       2) "lcw"
    127.0.0.1:6379> sscan myset 0 match *cw*
    1) "0"
    2) 1) "coder_lcw"
       2) "cwlin"
       3) "lcw"
    127.0.0.1:6379> sscan myset 0 match *chw*
    1) "0"
    2) 1) "chwlyn"
    
  • 应用:微博等网站的关注用户,QQ、微信的好友都可以放在一个集合中

    • 通过交集命令,可以得出共同关注或者共同好友
    • 通过差集/并集命令,可以进行好友推荐等功能

3.1.5、Hash(哈希)

  • Redis hash 是一个string类型的field和value的映射表,hash特别适合用于存储对象。

    • Set就是一种简化的Hash,只变动key,而value使用默认值填充。
    • 可以将一个Hash表作为一个对象进行存储,表中存放对象的信息。
  • 类似 Map 集合 —— key = {key = value},Hash 的相关操作都以 H 开头,常见命令如下:

    • HSET key field value: 将哈希表 key 中的字段 field 的值设为 value 。重复设置同一个field会覆盖,返回0
    • HMSET key field1 value1 [field2 value2..]: 同时将多个 field-value (域-值)对设置到哈希表 key 中。
    • HSETNX key field value: 只有在字段 field 不存在时,设置哈希表字段的值。
    • HEXISTS key field: 查看哈希表 key 中,指定的字段是否存在。
    • HGET key field value: 获取存储在哈希表中指定字段的值
    • HMGET key field1 [field2..]: 获取所有给定字段的值
    • HGETALL key: 获取在哈希表key 的所有字段和值
    • HKEYS key: 获取哈希表key中所有的字段
    • HLEN key: 获取哈希表中字段的数量
    • HVALS key: 获取哈希表中所有值
    • HDEL key field1 [field2..]: 删除哈希表key中一个/多个field字段
    • HINCRBY key field n: 为哈希表 key 中的指定字段的整数值加上增量n,并返回增量后结果 一样只适用于整数型字段
    • HINCRBYFLOAT key field n: 为哈希表 key 中的指定字段的浮点数值加上增量 n。
    • HSCAN key cursor [MATCH pattern] [COUNT count]: 迭代哈希表中的键值对。
  • Linux 操作实例:

    ------------------------HSET--HMSET--HSETNX----------------
    127.0.0.1:6379> HSET studentx name lcw # 将studentx哈希表作为一个对象,设置name为sakura
    (integer) 1
    127.0.0.1:6379> HSET studentx name cwlin # 重复设置field进行覆盖,并返回0
    (integer) 0
    127.0.0.1:6379> HSET studentx age 24 # 设置studentx的age为20
    (integer) 1
    127.0.0.1:6379> HMSET studentx sex 1 tel 12345678901 # 设置sex为1,tel为15623667886
    OK
    127.0.0.1:6379> HSETNX studentx name cwlin # HSETNX 设置已存在的field
    (integer) 0 # 失败
    127.0.0.1:6379> HSETNX studentx email 123456@qq.com
    (integer) 1 # 成功
    
    ----------------------HEXISTS--------------------------------
    127.0.0.1:6379> HEXISTS studentx name # name字段在studentx中是否存在
    (integer) 1 # 存在
    127.0.0.1:6379> HEXISTS studentx addr
    (integer) 0 # 不存在
    
    -------------------HGET--HMGET--HGETALL-----------
    127.0.0.1:6379> HGET studentx name # 获取studentx中name字段的value
    "cwlin"
    127.0.0.1:6379> HMGET studentx name age tel # 获取studentx中name、age、tel字段的value
    1) "cwlin"
    2) "24"
    3) "12345678901"
    127.0.0.1:6379> HGETALL studentx # 获取studentx中所有的field及其value
     1) "name"
     2) "cwlin"
     3) "age"
     4) "24"
     5) "sex"
     6) "1"
     7) "tel"
     8) "12345678901"
     9) "email"
    10) "123456@qq.com"
    
    
    --------------------HKEYS--HLEN--HVALS--------------
    127.0.0.1:6379> HKEYS studentx # 查看studentx中所有的field
    1) "name"
    2) "age"
    3) "sex"
    4) "tel"
    5) "email"
    127.0.0.1:6379> HLEN studentx # 查看studentx中的字段数量
    (integer) 5
    127.0.0.1:6379> HVALS studentx # 查看studentx中所有的value
    1) "cwlin"
    2) "24"
    3) "1"
    4) "12345678901"
    5) "123456@qq.com"
    
    -------------------------HDEL--------------------------
    127.0.0.1:6379> HDEL studentx sex tel # 删除studentx 中的sex、tel字段
    (integer) 2
    127.0.0.1:6379> HKEYS studentx
    1) "name"
    2) "age"
    3) "email"
    
    -------------HINCRBY--HINCRBYFLOAT------------------------
    127.0.0.1:6379> HINCRBY studentx age 1 # studentx的age字段数值+1
    (integer) 25
    127.0.0.1:6379> HINCRBY studentx name 1 # 非整数字型字段不可用
    (error) ERR hash value is not an integer
    127.0.0.1:6379> HINCRBYFLOAT studentx weight 0.6 # weight字段增加0.6
    "65.8"
    
  • 应用:Hash 用来存放经常变更数据、对象信息,尤其是用户信息之类的,经常变动的信息!

    • 存放一个对象:user = {name: age}
    • Hash更适合于对象的存储,Sring更加适合字符串存储!

3.1.6、Zset(有序集合)

  • 不同的是每个元素都会关联一个double类型的分数(score)。redis正是通过分数来为集合中的成员进行从小到大的排序。

    • 若score相同,则按字典顺序排序。
    • 有序集合的成员是唯一的,但分数(score)却可以重复。
  • 在插入时,可以增加一个 score 来进行分组排序,ZSet 的相关操作都是 Z 开头,常见命令如下:

    • ZADD key score member1 [score2 member2]: 向有序集合添加一个或多个成员,或者更新已存在成员的分数
      • ZADD 【key】 [ NX|XX ] [ CH ] [ INCR ] score member [score member …]
      • XX: 仅仅更新存在的成员,不添加新成员。
      • NX: 不更新存在的成员。只添加新成员。
      • CH: 修改返回值为发生变化的成员总数,原始是返回新添加成员的总数 (CH 是 changed 的意思)。更改的元素是新添加的成员,已经存在的成员更新分数。 所以在命令中指定的成员有相同的分数将不被计算在内。注:在通常情况下,ZADD返回值只计算新添加成员的数量。
      • INCR: 当ZADD指定这个选项时,成员的操作就等同ZINCRBY命令,对成员的分数进行递增操作。
    • ZCARD key: 获取有序集合的成员数
    • ZCOUNT key min max: 计算在有序集合中指定区间score的成员数
    • ZINCRBY key n member: 有序集合中对指定成员的分数加上增量 n
    • ZSCORE key member: 返回有序集中,成员的分数值
    • ZRANK key member: 返回有序集合中指定成员的索引
    • ZRANGE key start end [withscores]: 通过索引区间返回有序集合成指定区间内的成员(升序,下同)
      • withscores:显示 score ,如果需要显示直接在后面加上这个单词即可
    • ZRANGEBYLEX key min max: 通过字典区间返回有序集合的成员
    • ZRANGEBYSCORE key min max [withscores]: 通过分数返回有序集合指定区间内的成员,-inf 和 +inf分别表示最小最大值,只支持开区间()
    • ZLEXCOUNT key min max: 在有序集合中计算指定字典区间内成员数量
    • ZREM key member1 [member2..]: 移除有序集合中一个/多个成员
    • ZREMRANGEBYLEX key min max: 移除有序集合中给定的字典区间的所有成员
    • ZREMRANGEBYRANK key start stop: 移除有序集合中给定的排名区间的所有成员
    • ZREMRANGEBYSCORE key min max: 移除有序集合中给定的分数区间的所有成员
    • ZREVRANGE key start end [withscores]: 返回有序集中指定区间内的成员,通过索引,分数从高到底(降序,下同)
    • ZREVRANGEBYSCORRE key max min: 返回有序集中指定分数区间内的成员,分数从高到低排序
    • ZREVRANGEBYLEX key max min: 返回有序集中指定字典区间内的成员,按字典顺序倒序
    • ZREVRANK key member: 返回有序集合中指定成员的排名,有序集成员按分数值递减(从大到小)排序
    • ZINTERSTORE destination numkeys key1 [key2 ..]: 计算给定的一个或多个有序集的交集并将结果集存储在新的有序集合 key 中,numkeys:表示参与运算的集合数,将score相加作为结果的score
    • ZUNIONSTORE destination numkeys key1 [key2..]: 计算给定的一个或多个有序集的交集并将结果集存储在新的有序集合 key 中
    • ZSCAN key cursor [MATCH pattern\] [COUNT count]: 迭代有序集合中的元素(包括元素成员和元素分值)
  • Linux 操作实例:

    -------------------ZADD--ZCARD--ZCOUNT--------------
    127.0.0.1:6379> ZADD myzset 1 m1 2 m2 3 m3 # 向有序集合myzset中添加成员m1 score=1 以及成员m2 score=2..
    (integer) 2
    127.0.0.1:6379> ZCARD myzset # 获取有序集合的成员数
    (integer) 2
    127.0.0.1:6379> ZCOUNT myzset 0 1 # 获取score在 [0,1]区间的成员数量
    (integer) 1
    127.0.0.1:6379> ZCOUNT myzset 0 2
    (integer) 2
    
    ----------------ZINCRBY--ZSCORE--------------------------
    127.0.0.1:6379> ZINCRBY myzset 5 m2 # 将成员m2的score +5
    "7"
    127.0.0.1:6379> ZSCORE myzset m1 # 获取成员m1的score
    "1"
    127.0.0.1:6379> ZSCORE myzset m2
    "7"
    
    --------------ZRANK--ZRANGE-----------------------------------
    127.0.0.1:6379> ZRANK myzset m1 # 获取成员m1的索引,索引按照score排序,score相同索引值按字典顺序顺序增加
    (integer) 0
    127.0.0.1:6379> ZRANK myzset m2
    (integer) 2
    127.0.0.1:6379> ZRANGE myzset 0 1 # 获取索引在0~1的成员
    1) "m1"
    2) "m3"
    127.0.0.1:6379> ZRANGE myzset 0 -1 # 获取全部成员
    1) "m1"
    2) "m3"
    3) "m2"
    
    # testset=>{abc,add,amaze,apple,back,java,redis} score均为0
    ------------------ZRANGEBYLEX---------------------------------
    127.0.0.1:6379> ZRANGEBYLEX testset - + # 返回所有成员
    1) "abc"
    2) "add"
    3) "amaze"
    4) "apple"
    5) "back"
    6) "java"
    7) "redis"
    127.0.0.1:6379> ZRANGEBYLEX testset - + LIMIT 0 3 # 分页,按索引显示查询结果的 0,1,2 条记录
    1) "abc"
    2) "add"
    3) "amaze"
    127.0.0.1:6379> ZRANGEBYLEX testset - + LIMIT 3 3 # 显示 3,4,5 条记录
    1) "apple"
    2) "back"
    3) "java"
    127.0.0.1:6379> ZRANGEBYLEX testset (- [apple # 显示 (-,apple] 区间内的成员
    1) "abc"
    2) "add"
    3) "amaze"
    4) "apple"
    127.0.0.1:6379> ZRANGEBYLEX testset [apple [java # 显示 [apple,java]字典区间的成员
    1) "apple"
    2) "back"
    3) "java"
    
    -----------------------ZRANGEBYSCORE---------------------
    127.0.0.1:6379> ZRANGEBYSCORE myzset 1 10 # 返回score在 [1,10]之间的的成员
    1) "m1"
    2) "m3"
    3) "m2"
    127.0.0.1:6379> ZRANGEBYSCORE myzset 1 5
    1) "m1"
    2) "m3"
    
    --------------------ZLEXCOUNT-----------------------------
    127.0.0.1:6379> ZLEXCOUNT testset - +
    (integer) 7
    127.0.0.1:6379> ZLEXCOUNT testset [apple [java
    (integer) 3
    
    ------------------ZREM--ZREMRANGEBYLEX--ZREMRANGBYRANK--ZREMRANGEBYSCORE--------------------------------
    127.0.0.1:6379> ZREM testset abc # 移除成员abc
    (integer) 1
    127.0.0.1:6379> ZREMRANGEBYLEX testset [apple [java # 移除字典区间[apple,java]中的所有成员
    (integer) 3
    127.0.0.1:6379> ZREMRANGEBYRANK testset 0 1 # 移除排名0~1的所有成员
    (integer) 2
    127.0.0.1:6379> ZREMRANGEBYSCORE myzset 0 3 # 移除score在[0,3]的成员
    (integer) 2
    
    
    # testset => {abc,add,apple,amaze,back,java,redis} score均为0
    # myzset => {(m1,1),(m2,2),(m3,3),(m4,4),(m7,7),(m9,9)}
    ----------------ZREVRANGE--ZREVRANGEBYSCORE--ZREVRANGEBYLEX-----------
    127.0.0.1:6379> ZREVRANGE myzset 0 3 # 按score递减排序,然后按索引,返回结果的 0~3
    1) "m9"
    2) "m7"
    3) "m4"
    4) "m3"
    127.0.0.1:6379> ZREVRANGE myzset 2 4 # 返回排序结果的 索引的2~4
    1) "m4"
    2) "m3"
    3) "m2"
    127.0.0.1:6379> ZREVRANGEBYSCORE myzset 6 2 # 按score递减顺序 返回集合中分数在[2,6]之间的成员
    1) "m4"
    2) "m3"
    3) "m2"
    127.0.0.1:6379> ZREVRANGEBYLEX testset [java (add # 按字典倒序 返回集合中(add,java]字典区间的成员
    1) "java"
    2) "back"
    3) "apple"
    4) "amaze"
    
    -------------------------ZREVRANK------------------------------
    127.0.0.1:6379> ZREVRANK myzset m7 # 按score递减顺序,返回成员m7索引
    (integer) 1
    127.0.0.1:6379> ZREVRANK myzset m2
    (integer) 4
    
    
    # mathscore => {(xm,90),(xh,95),(xg,87)} 小明、小红、小刚的数学成绩
    # enscore => {(xm,70),(xh,93),(xg,90)} 小明、小红、小刚的英语成绩
    -------------------ZINTERSTORE--ZUNIONSTORE-----------------------------------
    127.0.0.1:6379> ZINTERSTORE sumscore 2 mathscore enscore # 将mathscore enscore进行合并 结果存放到sumscore
    (integer) 3
    127.0.0.1:6379> ZRANGE sumscore 0 -1 withscores # 合并后的score是之前集合中所有score的和
    1) "xm"
    2) "160"
    3) "xg"
    4) "177"
    5) "xh"
    6) "188"
    
    127.0.0.1:6379> ZUNIONSTORE lowestscore 2 mathscore enscore AGGREGATE MIN # 取两个集合的成员score最小值作为结果的
    (integer) 3
    127.0.0.1:6379> ZRANGE lowestscore 0 -1 withscores
    1) "xm"
    2) "70"
    3) "xg"
    4) "87"
    5) "xh"
    6) "93"
    
  • 应用:

    • set排序:存储班级成绩表、工资表排序!
    • 普通消息:1,重要消息:2,带权重进行判断
    • 学生成绩排序、排行榜应用实现,取Top N测试

3.2、三种特殊数据类型

3.2.1、Geospatial(地理位置)

官方文档 :https://www.redis.net.cn/order/3685.html

  • 查询一些地理位置的测试数据 :http://www.jsons.cn/lngcode/
  • 这个功能可以推算两地之间的距离,方圆几里内的人

Geospatial 相关的命令都以 GEO 开头,常用命令如下:

  • geoadd key longitud(经度) latitude(纬度) member [..]: 将具体经纬度的坐标存入一个有序集合

    • 有效的经度从-180度到180度。
    • 有效的纬度从-85.05112878度到85.05112878度。
    • 当坐标位置超出上述指定范围时,geoadd命令会返回一个错误。
    ### 规则:两级无法直接添加,我们一般会下载城市数据,直接通过java程序一次性导入
    127.0.0.1:6379> geoadd China:city 116.23128 40.22077 beijing
    (integer) 1
    127.0.0.1:6379> geoadd China:city 121.48941 31.40527 shanghai
    (integer) 1
    127.0.0.1:6379> geoadd China:city 106.54041 29.40268 chongqing
    (integer) 1
    127.0.0.1:6379> geoadd China:city 113.28063 23.12517 guangzhou 114.08594 22.5483 shenzhen
    (integer) 2
    
  • geopos key member [member..]: 获取集合中的一个/多个成员坐标

    127.0.0.1:6379> geopos China:city beijing
    1) 1) "116.23128265142440796"
       2) "40.22076905438526495"
    127.0.0.1:6379> geopos China:city shanghai
    1) 1) "121.48941010236740112"
       2) "31.40526993848380499"
    127.0.0.1:6379> geopos China:city guangzhou shenzhen
    1) 1) "113.28062742948532104"
       2) "23.12516983418487371"
    2) 1) "114.08593922853469849"
       2) "22.54830024969439961"
    
  • geodist key member1 member2 [unit]: 返回两个给定位置之间的距离。默认以米作为单位。

    • 指定单位的参数 unit 必须是以下单位之一:
      • m 表示单位为米。

      • km 表示单位为千米。

      • mi 表示单位为英里。

      • ft 表示单位为英尺。

    ### 如果两个位置之间的其中一个不存在, 那么命令返回空值。
    127.0.0.1:6379> geodist China:city guangzhou shenzhen
    "104553.4095"
    127.0.0.1:6379> geodist China:city shanghai guangzhou
    "1226603.4698"
    127.0.0.1:6379> geodist China:city shanghai guangzhou km
    "1226.6035"
    
  • georadius key longitude latitude radius m|km|mi|ft [WITHCOORD][WITHDIST] [WITHHASH] [COUNT count] [ASC | DESC]: 以给定的经纬度为中心, 返回集合包含的位置元素当中, 与中心的距离不超过给定最大距离的所有位置元素。

    • 通过 georadius 就可以完成 附近的人功能
    • WITHCOORD:带上坐标
    • WITHDIST:带上距离,单位与半径单位相同
    • WITHHASH: 以 52 位有符号整数的形式, 返回位置元素经过原始 geohash 编码的有序集合分值。 这个选项主要用于底层应用或者调试, 实际中的作用并不大。
    • COUNT n:只显示前n个(按距离递增排序)
    • ASC | DESC 表示排序规则:
      • ASC:根据中心的位置, 按照从近到远的方式返回位置元素。
      • DESC:根据中心的位置, 按照从远到近的方式返回位置元素。
    # 查询经纬度(120,30)坐标500km半径内的成
    127.0.0.1:6379> georadius China:city 120 30 500 km withcoord withdist员
    1) 1) "shanghai"
       2) "211.4652"
       3) 1) "121.48941010236740112"
          2) "31.40526993848380499"
    127.0.0.1:6379> georadius China:city 120 25 1000 km withcoord withdist
    1) 1) "shenzhen"
       2) "660.7579"
       3) 1) "114.08593922853469849"
          2) "22.54830024969439961"
    2) 1) "guangzhou"
       2) "713.4658"
       3) 1) "113.28062742948532104"
          2) "23.12516983418487371"
    3) 1) "shanghai"
       2) "727.2109"
       3) 1) "121.48941010236740112"
          2) "31.40526993848380499"
    127.0.0.1:6379> georadius China:city 120 25 500 km withcoord withdist
    (empty array)
    
  • GEORADIUSBYMEMBER key member radius...: 功能与GEORADIUS相同, 都可以找出位于指定范围内的元素,只是中心位置不是具体的经纬度,而是使用集合中已有的成员位置作为中心点。

    ### 找出指定元素周围的其他元素
    127.0.0.1:6379> georadiusbymember China:city guangzhou 1000 km withcoord withdist
    1) 1) "shenzhen"
       2) "104.5534"
       3) 1) "114.08593922853469849"
          2) "22.54830024969439961"
    2) 1) "guangzhou"
       2) "0.0000"
       3) 1) "113.28062742948532104"
          2) "23.12516983418487371"
    3) 1) "chongqing"
       2) "968.8206"
       3) 1) "106.54040783643722534"
          2) "29.40268053517299762"
    127.0.0.1:6379> georadiusbymember China:city beijing 500 km withcoord withdist
    1) 1) "beijing"
       2) "0.0000"
       3) 1) "116.23128265142440796"
          2) "40.22076905438526495"
    
  • geohash key member1 [member2..]: 返回一个或多个位置的11个字符的Geohash字符串表示,使用Geohash位置52点整数编码。

    • 他们可以缩短从右边的字符。它将失去精度,但仍将指向同一地区。
    1. 它可以在 geohash.org 网站使用(http://geohash.org/<geohash-string>)。例子:http://geohash.org/sqdtr74hyu0
    2. 与类似的前缀字符串是附近,但相反的是不正确的,这是可能的,用不同的前缀字符串附近。
    ### 获取指定元素经纬度坐标的geohash表示,如果两个字符串越接近,离的越近
    127.0.0.1:6379> geohash China:city beijing shanghai guangzhou shenzhen
    1) "wx4sucvncn0"
    2) "wtw6st1uuq0"
    3) "ws0e9cb3vu0"
    4) "ws10k0fc750"
    

应用

  • 朋友圈的定位、附近的人、打车距离计算
  • 获取所有人的位置信息,存放在一个集合中,然后筛选一定半径内的人

GEO 底层的实现原理就是 Zset ,可以使用 ZSet 命令来操作 GEO

  • 使用经纬度定位地理坐标,并用一个有序集合zset保存,所以zset命令也可以使用,具体如下:

    127.0.0.1:6379> zrange China:city 0 -1 # 用 ZSet 查询所有城市(元素)
    1) "chongqing"
    2) "shenzhen"
    3) "guangzhou"
    4) "shanghai"
    5) "beijing"
    127.0.0.1:6379> zrem China:city chongqing # 移除一个城市(元素)
    (integer) 1
    127.0.0.1:6379> zrange China:city 0 -1
    1) "shenzhen"
    2) "guangzhou"
    3) "shanghai"
    4) "beijing"
    

3.2.2、Hyperloglog(基数统计)

官方文档 :https://www.redis.net.cn/order/3629.htmlRedis

  • HyperLogLog 是用来做基数统计的算法,HyperLogLog 的优点是,在输入元素的数量或者体积非常非常大时,计算基数所需的空间总是固定的、并且是很小的。
  • HyperLogLog 占用的内存是固定的,花费 12 KB 内存,就可以计算接近 2^64 个不同元素的基数。
  • 因为 HyperLogLog 只会根据输入元素来计算基数,而不会储存输入元素本身,所以 HyperLogLog 不能像集合那样,返回输入的各个元素。
  • 其底层使用string数据类型

什么是基数?

  • 数据集中不重复的元素的个数,可以接受误差。

应用

  • 网页的访问量(UV):统计一个网站的访问人数,一个用户多次访问,也只能算作一个人。
    • 传统实现:存储用户的id,然后根据保存的 ID 的数量每次进行比较。若用户量过多,这种方式极其浪费空间,影响效率。
    • 我们的目的只是计数,而不是为了用户 ID,因此使用传统方法是不划算的。
    • 从内存角度来考虑,Hyperloglog 能够帮助我们利用最小的空间完成。
    • 但是 HyperLogLog 存在 0.81% 的错误率,但是对于统计访问人数等的功能来说,是可以接受的。

关于误差

  • 如果允许容错,那么一定可以使用 Hyperloglog!
  • 如果不允许容错,就使用set或者自己的数据类型即可!

Hyperloglog 相关的命令都以 PF 开头,常用命令如下:

  • PFADD key element1 [elememt2..]: 添加指定元素到 HyperLogLog中
  • PFCOUNT key [key]: 返回给定 HyperLogLog 的基数估算值。
  • PFMERGE destkey sourcekey [sourcekey..]: 将多个 HyperLogLog 合并为一个 HyperLogLog

Linux 操作实例:

------------------PFADD---PFCOUNT--------------------
127.0.0.1:6379> pfadd myname cwlin lcw chwlyn coder_lcw # 添加元素到myname
(integer) 1
127.0.0.1:6379> pfcount # 估算myname的基数
(integer) 4
127.0.0.1:6379> type myname # hyperloglog底层使用String类型
string
127.0.0.1:6379> pfadd mynickname cwlin chwlyn chw- ccccccchw # 添加元素到mynickname
(integer) 1
127.0.0.1:6379> pfcount myname
(integer) 4
127.0.0.1:6379> type myname
string

-----------------------PFMERGE-----------------------
127.0.0.1:6379> pfmerge name myname mynickname # 合并 myname 和 mynickname 到 name
OK
127.0.0.1:6379> pfcount name # 估算基数
(integer) 6

3.2.3、BitMaps(位图)

使用位存储,信息状态只有 0 和 1

  • BitMaps 也是一种数据结构,通过操作二进制位进行记录。
  • Bitmaps 是一串连续的2进制数字(0或1),每一位所在的位置为偏移(offset),在bitmaps上可执行AND,OR,XOR,NOT以及其它位操作。

应用场景:两个状态的,都可以使用bitmaps存储

  • 统计用户信息:签到统计、状态统计
  • 活跃、不活跃,已登录、未登录,已打卡、未打卡
  • 365天打卡:365天 = 365 bit,1字节 = 8bit,46个字节左右

BitMaps 相关的命令都以 BIT 开头或结尾,常用命令如下:

  • setbit key offset value: 为指定key的offset位设置值

  • getbit key offset: 获取offset位的值

  • bitcount key [start end]: 统计字符串被设置为1的bit数,也可以指定统计范围按字节

  • BITOP operation destkey key[key..]: 对一个或多个保存二进制位的字符串 key 进行位元操作,并将结果保存到 destkey 上。

    • BITOP 命令支持四个按位运算:ANDORXORNOT,因此调用该命令的有效形式为:

      • BITOP AND destkey srckey1 srckey2 srckey3 ... srckeyN

      • BITOP OR destkey srckey1 srckey2 srckey3 ... srckeyN

      • BITOP XOR destkey srckey1 srckey2 srckey3 ... srckeyN

      • BITOP NOT destkey srckey

    • 正如你可以看到,NOT 是特殊的,因为它只需要一个输入键,因为它执行比特反转,所以它只作为一元运算符有意义。

    • 操作结果始终存储在destkey

  • BITPOS key bit [start] [end]: 返回字符串里面第一个被设置为1或者0的bit位。

    • start 和 end 只能按字节,不能按位,其中第一个字节的最高有效位位于位置0,第二个字节的最高有效位位于位置8。
    • end 默认是字符串的最后一个字节。
    • 开始和结束可以包含负值,以便从字符串的末尾开始索引字节,其中-1是最后一个字节,-2是倒数第二个字符。

Linux 操作实例:

---------------setbit---getbit-----------------
127.0.0.1:6379> setbit sign 0 0 # 设置sign的第0位为 0
(integer) 0
127.0.0.1:6379> setbit sign 2 1 # 设置sign的第2位为 1,不设置默认是0
(integer) 0
127.0.0.1:6379> setbit sign 3 0
(integer) 0
127.0.0.1:6379> setbit sign 4 1
(integer) 0
127.0.0.1:6379> setbit sign 5 1
(integer) 0
127.0.0.1:6379> setbit sign 6 0
(integer) 0
127.0.0.1:6379> type sign
string
127.0.0.1:6379> getbit sign 4 # 获取第4位的数值
(integer) 1
127.0.0.1:6379> getbit sign 1 # 第1位未设置,默认是0
(integer) 0
127.0.0.1:6379> getbit sign 3
(integer) 0

------------------bitcount---------------------
127.0.0.1:6379> bitcount sign # 统计sign中为1的位数
(integer) 3

bitmaps的底层

  • 参考博客:https://juejin.cn/post/6999908907791417351

  • Bitmap 的底层数据结构用的是 String 类型的 SDS 数据结构来保存位数组,Redis 把每个字节数组的 8 个 bit 位利用起来,每个 bit 位表示一个元素的二值状态。

  • 为了直观展示,我们可以理解成 buf 数组的每个字节用一行表示,每一行有 8 个 bit 位,8 个格子分别表示这个字节中的 8 个 bit 位,如下图所示:

    figures\32、Redis(redis-bitmaps的底层原理)

    127.0.0.1:6379> set bitmaps_test abc
    OK # abc对应二进制:01100001 01100010 01100011
    127.0.0.1:6379> setbit bitmaps_test 6 1
    (integer) 0
    127.0.0.1:6379> get bitmaps_test
    "cbc"
    127.0.0.1:6379> setbit bitmaps_test 22 0
    (integer) 1
    127.0.0.1:6379> get bitmaps_test
    "cba"
    
  • 8 个 bit 组成一个 Byte,所以 Bitmap 会极大地节省存储空间。 这就是 Bitmap 的优势。

4、事务

  • Redis事务本质:一组命令的集合:----------------- 队列 set set get set 执行 -------------------
  • 事务中每条命令都会被序列化,在事务执行过程中按顺序执行,不允许其他命令进行干扰。
    • 一次性
    • 顺序性
    • 排他性
  • Redis事务没有隔离级别的概念
  • 所有的命令在事务中,在加入时并没有直接被执行,只有发起执行(Exec)命令的时候才会执行!
  • Redis单条命令是保证原子性的,但是Redis事务不能保证原子性!

4.1、Redis事务操作过程

  • 开启事务(multi
  • 命令入队(....
  • 执行事务(exec

执行事务(exec)

127.0.0.1:6379> multi # 开启事务
OK
127.0.0.1:6379> set k1 v1 # 命令入队
QUEUED
127.0.0.1:6379> set k2 v2 # ...
QUEUED
127.0.0.1:6379> get k1
QUEUED
127.0.0.1:6379> set k3 v3
QUEUED
127.0.0.1:6379> keys *
QUEUED
127.0.0.1:6379> exec # 执行事务
1) OK
2) OK
3) "v1"
4) OK
5) 1) "k3"
   2) "k2"
   3) "k1"

取消事务(discard)

127.0.0.1:6379> multi
OK
127.0.0.1:6379> set k1 v1
QUEUED
127.0.0.1:6379> set k2 v2
QUEUED
127.0.0.1:6379> discard # 取消事务
OK
127.0.0.1:6379> exec 
(error) ERR EXEC without MULTI # 当前未开启事务
127.0.0.1:6379> get k1 # 放弃事务后,命令并未执行
(nil)

4.2、事务错误

编译时异常(代码语法错误):事务中所有的命令都不执行

127.0.0.1:6379> multi
OK
127.0.0.1:6379> set k1 v1
QUEUED
127.0.0.1:6379> set k2 v2
QUEUED
127.0.0.1:6379> error k1 # 这是一条语法错误命令
(error) ERR unknown command `error`, with args beginning with: `k1`, # 会报错,但是不影响后续命令入队 
127.0.0.1:6379> set k3 v3
QUEUED
127.0.0.1:6379> EXEC
(error) EXECABORT Transaction discarded because of previous errors. # 执行报错
127.0.0.1:6379> get k2 
(nil) # 其他命令并没有被执行

运行时异常(代码逻辑错误):错误命令抛出异常,其他命令可以正常执行 >>> 因此,不保证事务原子性!

127.0.0.1:6379> multi
OK
127.0.0.1:6379> set k1 v1
QUEUED
127.0.0.1:6379> set k2 v2
QUEUED
127.0.0.1:6379> INCR k1 # 这条命令逻辑错误(对字符串进行增量)
QUEUED
127.0.0.1:6379> get k1
QUEUED
127.0.0.1:6379> exec
1) OK
2) OK
3) (error) ERR value is not an integer or out of range # 运行时报错
4) "v1" # 其他命令正常执行

# 虽然中间有一条命令报错了,但是后面的指令依旧正常执行成功了。
# 所以说Redis单条指令保证原子性,但是Redis事务不能保证原子性。

4.3、监控(面试常问)

  • **悲观锁:**很悲观,认为什么时候都会出现问题,无论做什么都会加锁!

  • **乐观锁:**很乐观,认为什么时候都不会出现问题,因此做什么都不会加锁!

    • 只是在更新数据的时候判断一下版本是否改变(在此期间是否有人修改过这个数据)
    • 获取 version,更新的时候比较 version
    • 在 MySQL 中用 Version 表示版本,在 Redis 中使用 watch key 监控指定数据,相当于乐观锁加锁
  • 如果事务执行成功,Redis 监控就会自动取消。

正常执行

127.0.0.1:6379> set money 100 # 余额:100
OK
127.0.0.1:6379> set use 0 # 支出:0
OK
127.0.0.1:6379> watch money # 监视money对象 (上锁)
OK
127.0.0.1:6379> multi # 事务正常结束,数据期间没有发生变动,这个时候就正常执行成功!
OK
127.0.0.1:6379(TX)> decrby money 20
QUEUED
127.0.0.1:6379(TX)> incrby use 20
QUEUED
127.0.0.1:6379(TX)> exec # 监视值没有被中途修改,事务正常执行
1) (integer) 80
2) (integer) 20

测试多线程修改值,使用watch可以当做redis的乐观锁操作(相当于getversion)

线程1:

127.0.0.1:6379> watch money # money上锁
OK
127.0.0.1:6379> multi
OK
127.0.0.1:6379(TX)> decrby money 20
QUEUED
127.0.0.1:6379(TX)> incrby use 20
QUEUED
127.0.0.1:6379(TX)> 	# 此时事务并没有执行

启动另一个客户端模拟线程插队,线程2:

127.0.0.1:6379> incrby money 900 # 修改了线程1中监视的money
(integer) 1000

回到线程1,执行事务:

127.0.0.1:6379(TX)> exec # 执行之前,线程2修改了我们的值,这个时候就会导致事务执行失败
(nil) # 没有结果,说明事务执行失败
127.0.0.1:6379> get money # 线程2修改生效
"1000"
127.0.0.1:6379> get use # 线程1事务执行失败,数值没有被修改
"0"

使用unwatch进行解锁获取最新值,然后再加锁进行事务。

127.0.0.1:6379> unwatch # 刷新一个事务中已被监视的所有key。
OK
127.0.0.1:6379> watch money # 重新监视money对象 (上锁)
OK
127.0.0.1:6379(TX)> multi
OK
127.0.0.1:6379(TX)> decrby money 20
QUEUED
127.0.0.1:6379(TX)> incrby use 20
QUEUED
127.0.0.1:6379(TX)> exec # 对比监视值是否变化,如果没有,事务正常执行;否则执行失败!
1) (integer) 980
2) (integer) 20

注意:每次提交执行exec后都会自动释放锁,不管是否成功

5、Jedis

使用Java来操作Redis,Jedis是Redis官方推荐使用的Java连接redis的客户端。

5.1、导入依赖

<!--导入jedis的包-->
<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>3.2.0</version>
</dependency>
<!--fastjson-->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.76</version>
</dependency>

5.2、编码测试

  • 连接数据库(https://blog.csdn.net/weixin_43878332/article/details/108741367

    1. 修改redis的配置文件

    2. 在云端安全组和防火墙上,开放端口 6379

    3. 修改防火墙服务,添加端口并重新载入

      firewall-cmd --state
      firewall-cmd --zone=public --permanent --add-port=6379/tcp
      firewall-cmd --reload
      firewall-cmd --list-all
      
    4. 重启redis-server

    5. 重新进入Redis需要密码验证

      [root@VM-4-12-centos src]# ./redis-server ../redis.conf
      [root@VM-4-12-centos src]# ./redis-cli
      127.0.0.1:6379> auth xxxxxx
      OK
      
  • 操作命令(TestPing.java

    public class TestPing {
        public static void main(String[] args) {
            Jedis jedis = new Jedis("192.168.xx.xxx", 6379);
            String response = jedis.ping();
            System.out.println(response); // PONG
            jedis.close();
        }
    }
    
  • 断开连接

5.3、常用的API

  • string、list、set、hash、zset
  • 所有的api命令,就是我们对应的上面学习的指令
public class TestKey {
    public static void main(String[] args) {
        Jedis jedis = new Jedis("192.168.xx.xxx", 6379);

        System.out.println("清空数据库 —— " + jedis.flushAll());
        System.out.println("判断某个键是否存在 —— "+jedis.exists("name"));
        System.out.println("新增<name:name> —— "+jedis.set("name","name"));
        System.out.println("新增<password:password> —— "+jedis.set("password","password"));
        System.out.println("所有的键 —— " +jedis.keys("*"));
        System.out.println("删除 password 的键值对 —— "+jedis.del("password"));
        System.out.println("获取 name 的值 —— "+jedis.get("name"));
        System.out.println("清空数据库 —— " + jedis.flushAll());

        jedis.close();
    }
}

/*
    清空数据库 —— OK
    判断某个键是否存在 —— false
    新增<name:name> —— OK
    新增<password:password> —— OK
    所有的键 —— [password, name]
    删除 password 的键值对 —— 1
    获取 name 的值 —— name
    清空数据库 —— OK
 */

5.4、事务

public class TestTX {
    public static void main(String[] args) {
        Jedis jedis = new Jedis("192.168.xx.xxx", 6379);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("name", "cwlin");
        jsonObject.put("gender", "man");

        jedis.flushDB();
        Transaction multi = jedis.multi(); // 开启事务
        String result = jsonObject.toJSONString();
        try {
            multi.set("user1", result);
            // jedis.watch(user1); // 监听
            multi.set("user2", result);
            // int i = 1 / 0; // 代码抛出异常,事务执行失败!
            multi.exec(); // 执行事务
        } catch (Exception e) {
            multi.discard(); // 放弃事务
        } finally {
            System.out.println(jedis.get("user1"));
            System.out.println(jedis.get("user2"));
            jedis.close(); // 关闭连接
        }
    }
}

6、SpringBoot 整合

6.1、概述

  • SpringBoot 操作数据都是使用 SpringData:jpa、jdbc、mongodb、redis等

  • SpringData 也是和 SpringBoot 齐名的项目

  • 说明:在 SpringBoot2.x 之后,原来使用的jedis 被替换为了 lettuce

    <dependency>
      <groupId>io.lettuce</groupId>
      <artifactId>lettuce-core</artifactId>
      <version>5.3.5.RELEASE</version>
      <scope>compile</scope>
    </dependency>
    
  • Jedis 和 lettuce 区别:

    • jedis:采用的是直连的 Service 服务,如果有多个线程操作的话是不安全的,如果想要避免不安全的操作,使用 Jedis Pool 连接池去解决,更像 BIO 模式
    • lettuce:底层采用 netty,实例可以在多个线程中进行共享,不存在线程不安全的情况!这样可以减少线程数据,性能更高,更像 NIO 模式

6.2、自动配置类源码分析

  • 在学习SpringBoot自动配置的原理时,整合一个组件并进行配置一定会有一个自动配置类xxxAutoConfiguration,并且在spring.factories中也一定能找到这个类的完全限定名,Redis也不例外

    spring-boot-autoconfigure-2.3.7.RELEASE.jar
    META-INF
    spring.factories
    org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration
    
  • 点击查看 RedisAutoConfiguration 自动配置类,发现绑定了一个 RedisProperties 配置文件

    //
    // Source code recreated from a .class file by IntelliJ IDEA
    // (powered by FernFlower decompiler)
    //
    
    package org.springframework.boot.autoconfigure.data.redis;
    
    import java.net.UnknownHostException;
    import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
    import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
    import org.springframework.boot.context.properties.EnableConfigurationProperties;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.context.annotation.Import;
    import org.springframework.data.redis.connection.RedisConnectionFactory;
    import org.springframework.data.redis.core.RedisOperations;
    import org.springframework.data.redis.core.RedisTemplate;
    import org.springframework.data.redis.core.StringRedisTemplate;
    
    @Configuration(
        proxyBeanMethods = false
    )
    @ConditionalOnClass({RedisOperations.class})
    @EnableConfigurationProperties({RedisProperties.class})
    @Import({LettuceConnectionConfiguration.class, JedisConnectionConfiguration.class})
    public class RedisAutoConfiguration {
        public RedisAutoConfiguration() {
        }
    
        @Bean
        @ConditionalOnMissingBean(name = {"redisTemplate"})
        public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
            RedisTemplate<Object, Object> template = new RedisTemplate();
            template.setConnectionFactory(redisConnectionFactory);
            return template;
        }
    
        @Bean
        @ConditionalOnMissingBean
        public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
            StringRedisTemplate template = new StringRedisTemplate();
            template.setConnectionFactory(redisConnectionFactory);
            return template;
        }
    }
    
  • 点击 RedisProperties 配置文件,查看 redis 可以配置的属性,以及连接池相关的配置。注意:使用时一定要使用 Lettuce 连接池

    @ConfigurationProperties(
        prefix = "spring.redis"
    )
    public class RedisProperties {
        private int database = 0;
        private String url;
        private String host = "localhost";
        private String password;
        private int port = 6379; // 默认端口
        private boolean ssl;
        private Duration timeout;
        private String clientName;
        private RedisProperties.Sentinel sentinel;
        private RedisProperties.Cluster cluster;
        private final RedisProperties.Jedis jedis = new RedisProperties.Jedis();
        private final RedisProperties.Lettuce lettuce = new RedisProperties.Lettuce();
        
        //......
        
        public static class Pool {
    		private int maxIdle = 8;
    		private int minIdle = 0;
    		private int maxActive = 8;
    		private Duration maxWait = Duration.ofMillis(-1);
    		private Duration timeBetweenEvictionRuns;
            
            //......
        }
    }
    
  • 回到 RedisAutoConfiguration 自动配置类,发现两个 Template 模板方法(对比RestTemplate、SqlSessionTemplate),可以使用这些 Template 来间接操作组件,RedisTemplate 和 StringRedisTemplate 分别用于操作 Redis 和 Redis 中的 String 数据类型。

    @Bean
    @ConditionalOnMissingBean(
        name = {"redisTemplate"}
    )
    // 可以自定义一个redisTemplate来替换默认的Redis模板!
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
        // 默认的 RedisTemplate 没有过多的设置,redis对象都是需要序列化!
    	// 两个泛型都是 Object, Object 的类型,我们后使用需要强制转换 <String, Object>
        RedisTemplate<Object, Object> template = new RedisTemplate();
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }
    
    @Bean
    @ConditionalOnMissingBean
    // 由于String是redis中最常使用的类型,因此单独提出来一个bean!
    public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
        StringRedisTemplate template = new StringRedisTemplate();
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }
    
  • 再注意到 RedisAutoConfiguration 自动配置类导入的两个类

    @Import({LettuceConnectionConfiguration.class, JedisConnectionConfiguration.class})
    
  • 先看 Jedis 的实现类 JedisConnectionConfiguration,其中 @ConditionalOnClass 注解中有两个类 GenericObjectPool.class 和 Jedis.class 默认是不存在的,因此 Jedis 是无法生效的

    @ConditionalOnClass({GenericObjectPool.class, JedisConnection.class, Jedis.class})
    
  • 再看 Lettuce 的实现类 LettuceConnectionConfiguration,其中 @ConditionalOnClass 注解的 RedisClient.class 类是可用的,因此 Lettuce 是正常生效的

    @ConditionalOnClass({RedisClient.class})
    

6.3、编码测试

  1. 导入依赖

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>
    
  2. 编写配置文件(配置属性详见 RedisProperties.class)

    # 配置redis
    spring.redis.host=192.168.xxx.xx
    spring.redis.port=6379
    spring.redis.password=xxxxxx
    # spring.redis.lettuce # 注意:使用连接池相关的配置时,一定要使用Lettuce连接池
    
  3. 使用RedisTemplate进行测试

    package com.cwlin;
    
    import org.junit.jupiter.api.Test;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.data.redis.core.RedisTemplate;
    
    @SpringBootTest
    class Redis02SpringBootApplicationTests {
        @Autowired
        private RedisTemplate redisTemplate;
    
        @Test
        void contextLoads() {
            /* redisTemplate 操作不同的数据类型,API 和 Redis 中的是一样的
             * opsForValue 类似于 Redis 中的 String
             * opsForList 类似于 Redis 中的 List
             * opsForSet 类似于 Redis 中的 Set
             * opsForHash 类似于 Redis 中的 Hash
             * opsForZSet 类似于 Redis 中的 ZSet
             * opsForGeo 类似于 Redis 中的 Geospatial
             * opsForHyperLogLog 类似于 Redis 中的 HyperLogLog
             */
    
            // 除了基本的操作,常用的命令都可以直接通过redisTemplate操作,比如事务和CURD。和数据库相关的操作都需要通过连接操作。
    
            /* 获取连接对象
             * RedisConnection connection = redisTemplate.getConnectionFactory().getConnection();
             * connection.flushDb();
             * connection.flushAll();
             */
    
            redisTemplate.opsForValue().set("myName", "cwlin");
            System.out.println(redisTemplate.opsForValue().get("myName"));
        }
    
    }
    
  4. 测试结果

    • 此时,我们回到Linux下查看Redis数据时,惊奇发现全是乱码,可是程序中可以正常输出。
    • 这时候就关系到存储对象的序列化问题,在网络中传输的对象也是一样需要序列化,否则就全是乱码。

6.4、序列化

6.4.1、源码分析

  • 在 RedisAutoConfiguration 类的 redisTemplate 方法中用到了一个 RedisTemplate 的对象

    @Bean
    @ConditionalOnMissingBean(name = {"redisTemplate"})
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
        RedisTemplate<Object, Object> template = new RedisTemplate();
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }
    
  • 默认的 RedisTemplate 内部的序列化配置是这样的,并查看这些序列化对象的赋值

    public class RedisTemplate<K, V> extends RedisAccessor implements RedisOperations<K, V>, BeanClassLoaderAware {
        private boolean enableTransactionSupport = false;
        private boolean exposeConnection = false;
        private boolean initialized = false;
        private boolean enableDefaultSerializer = true;
        
        // 序列化器
        @Nullable
        private RedisSerializer<?> defaultSerializer;
        @Nullable
        private ClassLoader classLoader;
        @Nullable
        private RedisSerializer keySerializer = null;
        @Nullable
        private RedisSerializer valueSerializer = null;
        @Nullable
        private RedisSerializer hashKeySerializer = null;
        @Nullable
        private RedisSerializer hashValueSerializer = null;
        private RedisSerializer<String> stringSerializer = RedisSerializer.string();
        
        // ...
    
        // 构造函数
        public RedisTemplate() {
        }
    
        public void afterPropertiesSet() {
            super.afterPropertiesSet();
            boolean defaultUsed = false;
            if (this.defaultSerializer == null) {
                // 默认的序列化方式是采用JDK序列化器,我们可能会采用Json来序列化
                this.defaultSerializer = new JdkSerializationRedisSerializer(this.classLoader != null ? this.classLoader : this.getClass().getClassLoader());
            }
    
            // 默认的RedisTemplate中的所有序列化器都是使用这个序列化器
            if (this.enableDefaultSerializer) {
                if (this.keySerializer == null) {
                    this.keySerializer = this.defaultSerializer;
                    defaultUsed = true;
                }
    
                if (this.valueSerializer == null) {
                    this.valueSerializer = this.defaultSerializer;
                    defaultUsed = true;
                }
    
                if (this.hashKeySerializer == null) {
                    this.hashKeySerializer = this.defaultSerializer;
                    defaultUsed = true;
                }
    
                if (this.hashValueSerializer == null) {
                    this.hashValueSerializer = this.defaultSerializer;
                    defaultUsed = true;
                }
            }
    
            if (this.enableDefaultSerializer && defaultUsed) {
                Assert.notNull(this.defaultSerializer, "default serializer null and not all serializers initialized");
            }
    
            if (this.scriptExecutor == null) {
                this.scriptExecutor = new DefaultScriptExecutor(this);
            }
    
            this.initialized = true;
        }
    	
        // ...
    }
    
  • 通过自定义 RedisTemplate 可以对其进行修改。

6.4.2、序列化测试

  1. 新建一个实体类

    package com.cwlin.pojo;
    
    import lombok.AllArgsConstructor;
    import lombok.Data;
    import lombok.NoArgsConstructor;
    import org.springframework.stereotype.Component;
    
    @Component
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    // 实体类序列化在后面加上 implements Serializable 
    public class User {
        private String name;
        private String age;
    }
    
  2. 编写测试类,先不序列化实体类

    package com.cwlin;
    
    import com.cwlin.pojo.User;
    import com.fasterxml.jackson.core.JsonProcessingException;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import org.junit.jupiter.api.Test;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.data.redis.core.RedisTemplate;
    
    @SpringBootTest
    class Redis02SpringBootApplicationTests {
        @Autowired
        private RedisTemplate redisTemplate;
    
        @Test
        void contextLoads() {
            // ...
        }
    
        @Test
        public void test() throws JsonProcessingException {
            User user = new User("cwlin","20");
            // 使用 JSON 序列化
            String jsonUser = new ObjectMapper().writeValueAsString(user);
            // 这里直接传入一个对象
            redisTemplate.opsForValue().set("user", jsonUser);
            System.out.println(redisTemplate.opsForValue().get("user"));
        }
    }
    
  3. 执行结果:在旧版中,不进行序列化会报序列化的错误;而在新版中,可以正常执行!一般实体类都要序列化

  4. **自定义 RedisTemplate 模板:**创建一个Bean加入容器,就会触发RedisTemplate上的条件注解,使得默认的RedisTemplate失效。

    • RedisSerializer提供了多种序列化方案:
      • 直接调用RedisSerializer的静态方法来返回序列化器,然后set;

      • 初始化相应的实现类,然后set。

    package com.cwlin.config;
    
    import com.fasterxml.jackson.annotation.JsonAutoDetect;
    import com.fasterxml.jackson.annotation.PropertyAccessor;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.data.redis.connection.RedisConnectionFactory;
    import org.springframework.data.redis.core.RedisTemplate;
    import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
    import org.springframework.data.redis.serializer.StringRedisSerializer;
    
    import java.net.UnknownHostException;
    
    @Configuration
    public class RedisConfig {
        @Bean
        public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
            // 将template 泛型设置为 <String, Object>
            RedisTemplate<String, Object> template = new RedisTemplate();
            // 连接工厂,不必修改
            template.setConnectionFactory(redisConnectionFactory);
    
            // 序列化设置
            // String序列化器
            StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
            // Json序列化器:使用 jackson 解析任意的对象
            Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
            // 使用 objectMapper 进行转义
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
            objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL);
            jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
    
            // key、hash的key 采用String序列化方式
            template.setKeySerializer(stringRedisSerializer); // 和RedisSerializer.string()等价
            template.setHashKeySerializer(stringRedisSerializer);
            // value、hash的value 采用Jackson序列化方式
            template.setValueSerializer(jackson2JsonRedisSerializer); // 和RedisSerializer.json()等价
            template.setHashValueSerializer(jackson2JsonRedisSerializer);
            // 把自定义的配置加入template中
            template.afterPropertiesSet();
            return template;
        }
    }
    
  5. 使用上述模板后,默认的RedisTemplate自动失效。只要对实体类进行序列化,就不会产生乱码了!如果去获取这个对象或者中文字符串的时候还是会显示转义字符,那么只需要在启动 Redis 客户端的时候加上 –raw 即可

    redis-cli --raw -p 6379
    

6.5、自定义Redis工具类

  • 使用 RedisTemplate 需要频繁调用 .opForxxx,然后才能进行对应的操作,这样使用起来代码效率低下,工作中一般不会这样使用,而是将这些常用的公共API抽取出来封装成为一个工具类,然后直接使用工具类来间接操作Redis,不但效率高并且易用。

  • 工具类参考博客:

  • 简单测试一下:

    package com.cwlin;
    
    import com.cwlin.pojo.User;
    import com.cwlin.utils.RedisUtil;
    import com.fasterxml.jackson.core.JsonProcessingException;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import org.junit.jupiter.api.Test;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.data.redis.core.RedisTemplate;
    
    @SpringBootTest
    class Redis02SpringBootApplicationTests {
        @Autowired
        private RedisTemplate redisTemplate;
    
        @Autowired
        private RedisUtil redisUtil;
    
        @Test
        public void utilTest() {
            redisUtil.set("name", "cwlin");
            System.out.println(redisUtil.get("name")); //会有反斜杠转义符
        }
    
        @Test
        void contextLoads() {
            // ...
        }
    
        @Test
        public void test() throws JsonProcessingException {
            // ...
        }
    }
    

7、Redis.conf

  1. units:容量单位不区分大小写,G和GB有区别

    # Note on units: when memory size is needed, it is possible to specify
    # it in the usual form of 1k 5GB 4M and so forth:
    #
    # 1k => 1000 bytes
    # 1kb => 1024 bytes
    # 1m => 1000000 bytes
    # 1mb => 1024*1024 bytes
    # 1g => 1000000000 bytes
    # 1gb => 1024*1024*1024 bytes
    #
    # units are case insensitive so 1GB 1Gb 1gB are all the same.
    
  2. INCLUDES:可以使用 include 组合多个配置问

    ################################## INCLUDES ###################################
    
    # Include one or more other config files here.  This is useful if you
    # have a standard template that goes to all Redis servers but also need
    # to customize a few per-server settings.  Include files can include
    # other files, so use this wisely.
    #
    # Notice option "include" won't be rewritten by command "CONFIG REWRITE"
    # from admin or Redis Sentinel. Since Redis always uses the last processed
    # line as value of a configuration directive, you'd better put includes
    # at the beginning of this file to avoid overwriting config change at runtime.
    #
    # If instead you are interested in using includes to override configuration
    # options, it is better to use include as the last line.
    #
    # include /path/to/local.conf
    # include /path/to/other.conf
    
  3. MODULES:加载其他的模块(略)

    ################################## MODULES #####################################
    
    # Load modules at startup. If the server is not able to load modules
    # it will abort. It is possible to use multiple loadmodule directives.
    #
    # loadmodule /path/to/my_module.so
    # loadmodule /path/to/other_module.so
    
  4. NETWORK:网络配置(重点!)

    • 默认情况下,如果没有指定 bind 配置指令,Redis将监听服务器上所有可用网络接口的连接;使用 bind 配置指令,后跟一个或多个IP地址,可以只监听一个或多个选定的接口。
    • 在这里,注释掉 bind 指令,方便 Java 通过 Jedis 或 SpringBoot 远程连接。
    ################################## NETWORK #####################################
    
    # By default, if no "bind" configuration directive is specified, Redis listens
    # 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 192.168.1.100 10.0.0.1
    # 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  
    
    • protected-mode是个安全保护层, 目的是避免在 internet 上开放的 Redis 实例被访问和利用。
    • 默认情况下,已启用保护模式。只有当希望其他主机的客户机连接到 Redis 时,才应该禁用它。
    • 在这里,关闭保护模式,方便 Java 通过 Jedis 或 SpringBoot 远程连接。
    # Protected mode is a layer of security protection, in order to avoid that
    # Redis instances left open on the internet are accessed and exploited.
    #
    # When protected mode is on and if:
    #
    # 1) The server is not binding explicitly to a set of addresses using the
    #    "bind" directive.
    # 2) No password is configured.
    #
    # The server only accepts connections from clients connecting from the
    # IPv4 and IPv6 loopback addresses 127.0.0.1 and ::1, and from Unix domain
    # sockets.
    #
    # 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
    
    • 端口号配置,默认是6379
    # 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
    
    • TCP 连接的相关配置:
    # TCP listen() backlog.  # TCP积压工作
    #
    # In high requests-per-second environments you need an high backlog in order
    # to avoid slow clients connections issues. Note that the Linux kernel
    # will silently truncate it to the value of /proc/sys/net/core/somaxconn so
    # make sure to raise both the value of somaxconn and tcp_max_syn_backlog
    # in order to get the desired effect.
    tcp-backlog 511
    
    # Unix socket.  # Unix套接字
    #
    # Specify the path for the Unix socket that will be used to listen for
    # incoming connections. There is no default, so Redis will not listen
    # on a unix socket when not specified.
    #
    # unixsocket /tmp/redis.sock
    # unixsocketperm 700
    
    # Close the connection after a client is idle for N seconds (0 to disable)
    timeout 5000  # 当空闲5000秒后关闭
    
    # TCP keepalive.
    #
    # If non-zero, use SO_KEEPALIVE to send TCP ACKs to clients in absence
    # of communication. This is useful for two reasons:
    #
    # 1) Detect dead peers.
    # 2) Take the connection alive from the point of view of network
    #    equipment in the middle.
    #
    # On Linux, the specified value (in seconds) is the period used to send ACKs.
    # Note that to close the connection the double of the time is needed.
    # On other kernels the period depends on the kernel configuration.
    #
    # A reasonable value for this option is 300 seconds, which is the new
    # Redis default starting with Redis 3.2.1.
    tcp-keepalive 300  # 每300秒没有收到上层协议的数据,就发送一个空报文,来确认对方是否还在线
    
  5. GENERAL:通用配置(进程、日志等)

    • daemonize:默认情况下,Redis不会作为守护程序运行,即后台运行。在这里,我们将它开启。
    • supervised:用于管理守护进程,具体有四种配置。
    • redis.pid:配置文件的pid文件,如果以后台方式运行,就需要指定一个pid文件。
    ################################# GENERAL #####################################
    
    # By default Redis does not run as a daemon. Use 'yes' if you need it.
    # Note that Redis will write a pid file in /var/run/redis.pid when daemonized.
    daemonize yes
    
    # If you run Redis from upstart or systemd, Redis can interact with your
    # supervision tree. Options:
    #   supervised no      - no supervision interaction
    #   supervised upstart - signal upstart by putting Redis into SIGSTOP mode
    #   supervised systemd - signal systemd by writing READY=1 to $NOTIFY_SOCKET
    #   supervised auto    - detect upstart or systemd method based on
    #                        UPSTART_JOB or NOTIFY_SOCKET environment variables
    # Note: these supervision methods only signal "process is ready."
    #       They do not enable continuous liveness pings back to your supervisor.
    supervised no
    
    # If a pid file is specified, Redis writes it where specified at startup
    # and removes it at exit.
    #
    # When the server runs non daemonized, no pid file is created if none is
    # specified in the configuration. When the server is daemonized, the pid file
    # is used even if not specified, defaulting to "/var/run/redis.pid".
    #
    # Creating a pid file is best effort: if Redis is not able to create it
    # nothing bad happens, the server will start and run normally.
    pidfile /www/server/redis/redis.pid 
    
    • loglevel:日志输出级别,具体有四个级别:
      • debug(大量信息,对开发/测试有用)
      • verbose(许多很少有用的信息,但不像调试级别那样混乱)
      • notice(适度冗长,可能是你想要的生产环境
      • warning(只记录非常重要/关键的消息
    • logfile:日志输出文件,如果为空,则是一个标准的输出
    • syslog:系统日志
      • 要启用对系统记录器的日志记录,只需将”syslog enabled“设置为yes,并根据需要更新其他syslog参数。
      • syslog-ident:指定系统日志标识
      • syslog-facility:指定系统日志工具 LOCAL0 ~ LOCAL7
    # Specify the server verbosity level.
    # This can be one of:
    # debug (a lot of information, useful for development/testing)
    # verbose (many rarely useful info, but not a mess like the debug level)
    # notice (moderately verbose, what you want in production probably)
    # warning (only very important / critical messages are logged)
    loglevel notice
    
    # Specify the log file name. Also the empty string can be used to force
    # Redis to log on the standard output. Note that if you use standard
    # output for logging but daemonize, logs will be sent to /dev/null
    logfile "/www/server/redis/redis.log"
    
    # To enable logging to the system logger, just set 'syslog-enabled' to yes,
    # and optionally update the other syslog parameters to suit your needs.
    # syslog-enabled no
    
    # Specify the syslog identity.
    # syslog-ident redis
    
    # Specify the syslog facility. Must be USER or between LOCAL0-LOCAL7.
    # syslog-facility local0
    
    • databases:配置数据库的数量,默认是16个数据库,默认数据库为 DB 0。
    • always-show-logo:配置是否总是显示 logo,默认是开启。
    # Set the number of databases. The default database is DB 0, you can select
    # a different one on a per-connection basis using SELECT <dbid> where
    # dbid is a number between 0 and 'databases'-1
    databases 16
    
    # By default Redis shows an ASCII art logo only when started to log to the
    # standard output and if the standard output is a TTY. Basically this means
    # that normally a logo is displayed only in interactive sessions.
    #
    # However it is possible to force the pre-4.0 behavior and always show a
    # ASCII art logo in startup logs by setting the following option to yes.
    always-show-logo yes
    
  6. SNAPSHOTTING(快照):持久化规则

    • 持久化:在一定时间(秒)内,对数据库执行了一定数量的写操作,则会把数据持久化到文件 .rdb. aof。学习持久化后,可以自定义这个配置!

    • 持久化方式:RDB 和 AOF。

    • 由于 Redis 是基于内存的数据库(内存数据库),需要将数据由内存持久化到文件中。如果没有持久化,那么数据断电及失!

    ################################ SNAPSHOTTING  ################################
    #
    # Save the DB on disk:
    #
    #   save <seconds> <changes>
    #
    #   Will save the DB if both the given number of seconds and the given
    #   number of write operations against the DB occurred.
    #
    #   In the example below the behaviour will be to save:
    #   after 900 sec (15 min) if at least 1 key changed
    #   after 300 sec (5 min) if at least 10 keys changed
    #   after 60 sec if at least 10000 keys changed
    #
    #   Note: you can disable saving completely by commenting out all "save" lines.
    #
    #   It is also possible to remove all the previously configured save
    #   points by adding a save directive with a single empty string argument
    #   like in the following example:
    #
    #   save ""
    
    save 900 1  # 如果 900 秒内至少有 1 个key进行了修改,我们就进行持久化操作
    save 300 10  # 如果 300 秒内至少有 10 个key进行了修改,我们就进行持久化操作
    save 60 10000  # 如果 60 秒内至少有 10000 个key进行了修改,我们就进行持久化操作
    
    # By default Redis will stop accepting writes if RDB snapshots are enabled
    # (at least one save point) and the latest background save failed.
    # This will make the user aware (in a hard way) that data is not persisting
    # on disk properly, otherwise chances are that no one will notice and some
    # disaster will happen.
    #
    # If the background saving process will start working again Redis will
    # automatically allow writes again.
    #
    # However if you have setup your proper monitoring of the Redis server
    # and persistence, you may want to disable this feature so that Redis will
    # continue to work as usual even if there are problems with disk,
    # permissions, and so forth.
    stop-writes-on-bgsave-error yes  # 持久化出错后,是否继续工作
    
    # Compress string objects using LZF when dump .rdb databases?
    # For default that's set to 'yes' as it's almost always a win.
    # If you want to save some CPU in the saving child set it to 'no' but
    # the dataset will likely be bigger if you have compressible values or keys.
    rdbcompression yes  # 是否压缩rdb文件,需要消耗一些cpu的资源
    
    # Since version 5 of RDB a CRC64 checksum is placed at the end of the file.
    # This makes the format more resistant to corruption but there is a performance
    # hit to pay (around 10%) when saving and loading RDB files, so you can disable it
    # for maximum performances.
    #
    # RDB files created with checksum disabled have a checksum of zero that will
    # tell the loading code to skip the check.
    rdbchecksum yes  # 在保存rdb文件时,进行错误的检查校验
    
    # The filename where to dump the DB
    dbfilename dump.rdb  # 持久化生成的rdb文件名
    
    # The working directory.
    #
    # The DB will be written inside this directory, with the filename specified
    # above using the 'dbfilename' configuration directive.
    #
    # The Append Only File will also be created inside this directory.
    #
    # Note that you must specify a directory here, not a file name.
    dir /www/server/redis/   # rdb文件保存的目录,默认为当前目录
    
  7. REPLICATION:主从复制(这里暂时不展开介绍)

    ################################# REPLICATION #################################
    
    # Master-Replica replication. Use replicaof to make a Redis instance a copy of
    # another Redis server. A few things to understand ASAP about Redis replication.
    #
    #   +------------------+      +---------------+
    #   |      Master      | ---> |    Replica    |
    #   | (receive writes) |      |  (exact copy) |
    #   +------------------+      +---------------+
    #
    # 1) Redis replication is asynchronous, but you can configure a master to
    #    stop accepting writes if it appears to be not connected with at least
    #    a given number of replicas.
    # 2) Redis replicas are able to perform a partial resynchronization with the
    #    master if the replication link is lost for a relatively small amount of
    #    time. You may want to configure the replication backlog size (see the next
    #    sections of this file) with a sensible value depending on your needs.
    # 3) Replication is automatic and does not need user intervention. After a
    #    network partition replicas automatically try to reconnect to masters
    #    and resynchronize with them.
    
    # ......
    
  8. SECURITY:安全配置

    • requirepass:设置密码认证,在云服务器上一定要设置密码!

      • 通过修改配置文件进行设置,记得重启 redis。

      • 通过命令进行设置:config set requirepass xxxxxx,关闭进程后密码会失效。

      • 使用密码进行登录:

        127.0.0.1:6379> ping
        (error) NOAUTH Authentication required.
        127.0.0.1:6379> auth xxxxxx
        OK
        
    • Redis 6.0 后,建议使用外部 ACL代替。(略)

    ################################## SECURITY ###################################
    
    # Require clients to issue AUTH <PASSWORD> before processing any other
    # commands.  This might be useful in environments in which you do not trust
    # others with access to the host running redis-server.
    #
    # This should stay commented out for backward compatibility and because most
    # people do not need auth (e.g. they run their own servers).
    #
    # Warning: since Redis is pretty fast an outside user can try up to
    # 150k passwords per second against a good box. This means that you should
    # use a very strong password otherwise it will be very easy to break.
    #
    requirepass xxxxxx
    
    # Command renaming.
    #
    # It is possible to change the name of dangerous commands in a shared
    # environment. For instance the CONFIG command may be renamed into something
    # hard to guess so that it will still be available for internal-use tools
    # but not available for general clients.
    #
    # Example:
    #
    # rename-command CONFIG b840fc02d524045429941cc15f59e41cb7be6c52
    #
    # It is also possible to completely kill a command by renaming it into
    # an empty string:
    #
    # rename-command CONFIG ""
    #
    # Please note that changing the name of commands that are logged into the
    # AOF file or transmitted to replicas may cause problems.
    
  9. CLIENT:设置连接 Redis 的最大客户端数量

    ################################### CLIENTS ####################################
    
    # Set the max number of connected clients at the same time. By default
    # this limit is set to 10000 clients, however if the Redis server is not
    # able to configure the process file limit to allow for the specified limit
    # the max number of allowed clients is set to the current file limit
    # minus 32 (as Redis reserves a few file descriptors for internal uses).
    #
    # Once the limit is reached Redis will close all the new connections sending
    # an error 'max number of clients reached'.
    #
    # maxclients 10000
    
  10. MEMORY MANAGEMENT:内存管理

    • maxmemory <bytes>:设置 redis 最大的内存容量
    • maxmemory-policy noeviction:设置内存达到上限的处理策略,命令设置方式:config set maxmemory-policy noeviction
      • noeviction:不删除策略;达到最大内存限制时, 如果需要更多内存,直接返回错误信息,不会删除任何键值。(默认值
      • allkeys-lru:所有 key 通用;使用 LRU 算法(Less Recently Used, LRU)优先删除最近最少使用的键值。
      • volatile-lru:只限于设置了 expire 的部分;使用 LRU 算法从设置了过期时间的键集合中优先删除最近最少使用的键值。
      • allkeys-random:所有 key 通用;从所有 key 中随机删除一部分。
      • volatile-random:只限于设置了 expire 的部分;从设置了过期时间的键集合中随机删除一部分。
      • volatile-ttl:只限于设置了 expire 的部分;使用 TTL 算法(Time To Live, TTL)从设置了过期时间的键集合中优先删除剩余时间最短的键值。
      • allkeys-lfu:所有 key 通用;使用 LFU 算法(Least Frequently Used, LFU)优先删除使用频率最少的键值。
      • volatile-lfu:只限于设置了 expire 的部分;使用 LFU 算法从设置了过期时间的键集合中优先删除使用频率最少的键值。
    • maxmeory-samples:默认值为 5,redis 不会准确地删除所有键中**最近最少使用(LRU)**的键,而是随机抽取 maxmeory-samples 个键,删除这 5 个键中最近最少使用的键
    ############################## MEMORY MANAGEMENT ################################
    
    # Set a memory usage limit to the specified amount of bytes.
    # When the memory limit is reached Redis will try to remove keys
    # according to the eviction policy selected (see maxmemory-policy).
    #
    # If Redis can't remove keys according to the policy, or if the policy is
    # set to 'noeviction', Redis will start to reply with errors to commands
    # that would use more memory, like SET, LPUSH, and so on, and will continue
    # to reply to read-only commands like GET.
    #
    # This option is usually useful when using Redis as an LRU or LFU cache, or to
    # set a hard memory limit for an instance (using the 'noeviction' policy).
    #
    # WARNING: If you have replicas attached to an instance with maxmemory on,
    # the size of the output buffers needed to feed the replicas are subtracted
    # from the used memory count, so that network problems / resyncs will
    # not trigger a loop where keys are evicted, and in turn the output
    # buffer of replicas is full with DELs of keys evicted triggering the deletion
    # of more keys, and so forth until the database is completely emptied.
    #
    # In short... if you have replicas attached it is suggested that you set a lower
    # limit for maxmemory so that there is some free RAM on the system for replica
    # output buffers (but this is not needed if the policy is 'noeviction').
    #
    # maxmemory <bytes>
    
    # MAXMEMORY POLICY: how Redis will select what to remove when maxmemory
    # is reached. You can select among five behaviors:
    #
    # volatile-lru -> Evict using approximated LRU among the keys with an expire set.
    # allkeys-lru -> Evict any key using approximated LRU.
    # volatile-lfu -> Evict using approximated LFU among the keys with an expire set.
    # allkeys-lfu -> Evict any key using approximated LFU.
    # volatile-random -> Remove a random key among the ones with an expire set.
    # allkeys-random -> Remove a random key, any key.
    # volatile-ttl -> Remove the key with the nearest expire time (minor TTL)
    # noeviction -> Don't evict anything, just return an error on write operations.
    #
    # LRU means Least Recently Used
    # LFU means Least Frequently Used
    #
    # Both LRU, LFU and volatile-ttl are implemented using approximated
    # randomized algorithms.
    #
    # Note: with any of the above policies, Redis will return an error on write
    #       operations, when there are no suitable keys for eviction.
    #
    #       At the date of writing these commands are: set setnx setex append
    #       incr decr rpush lpush rpushx lpushx linsert lset rpoplpush sadd
    #       sinter sinterstore sunion sunionstore sdiff sdiffstore zadd zincrby
    #       zunionstore zinterstore hset hsetnx hmset hincrby incrby decrby
    #       getset mset msetnx exec sort
    #
    # The default is:
    #
    # maxmemory-policy noeviction
    
    # LRU, LFU and minimal TTL algorithms are not precise algorithms but approximated
    # algorithms (in order to save memory), so you can tune it for speed or
    # accuracy. For default Redis will check five keys and pick the one that was
    # used less recently, you can change the sample size using the following
    # configuration directive.
    #
    # The default of 5 produces good enough results. 10 Approximates very closely
    # true LRU but costs more CPU. 3 is faster but not very accurate.
    #
    # maxmemory-samples 5
    
    # Starting from Redis 5, by default a replica will ignore its maxmemory setting
    # (unless it is promoted to master after a failover or manually). It means
    # that the eviction of keys will be just handled by the master, sending the
    # DEL commands to the replica as keys evict in the master side.
    #
    # This behavior ensures that masters and replicas stay consistent, and is usually
    # what you want, however if your replica is writable, or you want the replica to have
    # a different memory setting, and you are sure all the writes performed to the
    # replica are idempotent, then you may change this default (but be sure to understand
    # what you are doing).
    #
    # Note that since the replica by default does not evict, it may end using more
    # memory than the one set via maxmemory (there are certain buffers that may
    # be larger on the replica, or data structures may sometimes take more memory and so
    # forth). So make sure you monitor your replicas and make sure they have enough
    # memory to never hit a real out-of-memory condition before the master hits
    # the configured maxmemory setting.
    #
    # replica-ignore-maxmemory yes
    
  11. APPEND ONLY MODE:AOF 配置

    • appendonly no:默认不开启 AOF 模式,默认使用 RDB 持久化方式,大部分情况下 RDB 足够使用
    • appendfilename:AOF 持久化文件的文件名
    • appendfsync:数据同步策略
      • # appendfsync always:每次修改都会 sync,消耗性能!
      • appendfsync everysec:每秒执行一次 sync,可能会丢失这 1s 的数据!
      • # appendfsync no:不执行 sync,这个时候操作系统自己同步数据,速度最快!
    ############################## APPEND ONLY MODE ###############################
    
    # By default Redis asynchronously dumps the dataset on disk. This mode is
    # good enough in many applications, but an issue with the Redis process or
    # a power outage may result into a few minutes of writes lost (depending on
    # the configured save points).
    #
    # The Append Only File is an alternative persistence mode that provides
    # much better durability. For instance using the default data fsync policy
    # (see later in the config file) Redis can lose just one second of writes in a
    # dramatic event like a server power outage, or a single write if something
    # wrong with the Redis process itself happens, but the operating system is
    # still running correctly.
    #
    # AOF and RDB persistence can be enabled at the same time without problems.
    # If the AOF is enabled on startup Redis will load the AOF, that is the file
    # with the better durability guarantees.
    #
    # Please check http://redis.io/topics/persistence for more information.
    
    appendonly no
    
    # The name of the append only file (default: "appendonly.aof")
    
    appendfilename "appendonly.aof"
    
    # The fsync() call tells the Operating System to actually write data on disk
    # instead of waiting for more data in the output buffer. Some OS will really flush
    # data on disk, some other OS will just try to do it ASAP.
    #
    # Redis supports three different modes:
    #
    # no: don't fsync, just let the OS flush the data when it wants. Faster.
    # always: fsync after every write to the append only log. Slow, Safest.
    # everysec: fsync only one time every second. Compromise.
    #
    # The default is "everysec", as that's usually the right compromise between
    # speed and data safety. It's up to you to understand if you can relax this to
    # "no" that will let the operating system flush the output buffer when
    # it wants, for better performances (but if you can live with the idea of
    # some data loss consider the default persistence mode that's snapshotting),
    # or on the contrary, use "always" that's very slow but a bit safer than
    # everysec.
    #
    # More details please check the following article:
    # http://antirez.com/post/redis-persistence-demystified.html
    #
    # If unsure, use "everysec".
    
    # appendfsync always
    appendfsync everysec
    # appendfsync no
    
    # When the AOF fsync policy is set to always or everysec, and a background
    # saving process (a background save or AOF log background rewriting) is
    # performing a lot of I/O against the disk, in some Linux configurations
    # Redis may block too long on the fsync() call. Note that there is no fix for
    # this currently, as even performing fsync in a different thread will block
    # our synchronous write(2) call.
    

8、Redis 持久化(面试重点)

  • Redis 是内存数据库,如果不将内存中的数据库状态保存到磁盘中,那么一旦服务器进程退出,服务器中的数据库状态也会消失。
  • 因此,Redis 提供了持久化功能。

8.1、持久化 - RDB(Redis DataBase)

8.1.1、什么是 RDB

  • 在指定时间间隔内,将内存中的数据集写入磁盘,也就是 Snapshot 快照,在恢复时,将快照文件直接读取到内存里,进行数据的恢复;
  • Redis会单独创建(fork)一个子进程来进行持久化,会先将书局写入到一个临时文件中,待持久化过程都结束了。再用这个临时文件替换上次持久化好的文件。整个过程中,主进程是不进行任何IO操作的,这就确保了极高的性能。如果需要大规模数据的恢复,且对于数据恢复的完整性不是非常敏感,那RDB方式要比AOF更加高效,RDB的缺点是最后一次持久化后的数据可能丢失。我们默认的就是RDB,一般情况下不需要修改这个配置。

image.png

  • 默认情况下, Redis 将数据库快照保存在名字为 dump.rdb 的二进制文件中,文件名可以在配置文件中进行自定义。

在这里插入图片描述

8.1.2、工作原理

  • 在进行 RDB 的时候,redis 的主线程是不会做 io 操作的,主线程会 fork 一个子线程来完成该操作
    1. Redis 调用 forks,同时拥有父进程和子进程。
    2. 子进程将数据集写入到一个临时 RDB 文件中。
    3. 当子进程完成对新 RDB 文件的写入时,Redis 用新 RDB 文件替换原来的 RDB 文件,并删除旧的 RDB 文件。
  • 这种工作方式使得 Redis 可以从写时复制(copy-on-write)机制中获益(因为是使用子进程进行写操作,而父进程依然可以接收来自客户端的请求。)

在这里插入图片描述

8.1.3、触发机制

  • 持久化:在一定时间(秒)内,对数据库执行了一定数量的写操作,则会把数据持久化到文件:
    1. 在 save 的规则满足的情况下,会自动触发 rdb 原则
    2. 执行 flushall命令,也会触发我们的 rdb 原则
    3. 退出 redis,也会自动产生 rdb 文件

在这里插入图片描述

8.1.3.1、save
  • 使用 save 命令,会立刻对当前内存中的数据进行持久化,但是会阻塞,也就是不接受其他操作了。
  • 由于 save 是同步命令,会占用Redis的主进程。若Redis数据非常多时,save 命令执行速度会非常慢,阻塞所有客户端的请求。

在这里插入图片描述

8.1.3.2、bgsave
  • bgsave 是异步进行,进行持久化的时候,redis 还可以将继续响应客户端请求。

在这里插入图片描述

8.1.3.3、bgsave和save对比
命令savebgsave
IO类型同步异步
阻塞?是(阻塞发生在fock(),通常非常快)
复杂度O(n)O(n)
优点不会消耗额外的内存不阻塞客户端命令
缺点阻塞客户端命令需要fock子进程,消耗内存

8.1.4、恢复数据

  1. 只需要把 RDB 文件放到 Redis 的启动目录,Redis 启动的时候就会自动检查 dump.rdb 文件,并恢复数据。

  2. 查看 Redis 的启动目录,即 RDB 文件需要存在的位置:

    127.0.0.1:6379> config get dir
    1) "dir"
    2) "/www/server/redis"  # 如果在这个目录下存在dump.rdb文件,启动就会自动恢复其中的数据
    
  3. 在生产环境下,一般会把这个 RDB 文件进行备份。在实际使用中,RDB 都是放在从机上面备用。

8.1.5、优缺点

  • 优点:
    1. 适合大规模的数据恢复
    2. 对数据的完整性要求不高
  • 缺点:
    1. 需要一定的时间间隔进行操作,如果 redis 意外宕机了,那么最后一次修改的数据就没有了。
    2. 在 fork 进程时,会占用一定的内容空间。

8.2、持久化 - AOF(Append Only File)

  • 快照功能(RDB)并不是非常耐久(durable): 如果 Redis 因为某些原因而造成故障停机, 那么服务器将丢失最近写入、以及未保存到快照中的那些数据。
  • 从 1.1 版本开始, Redis 增加了一种完全耐久的持久化方式: AOF 持久化。

8.2.1、什么是 AOF

  • 将所有的命令都记录下来,类似于一个 history 文件,恢复数据的时候就把这里面的数据都执行一遍。
  • 以日志的形式来记录每个写的操作,将Redis执行过的所有指令记录下来(读操作不记录),只许追加文件但不可以改写文件,redis启动之初会读取该文件重新构建数据,换言之,redis重启的话就根据日志文件的内容将写指令从前到后执行一次以完成数据的恢复工作。

在这里插入图片描述

  • AOF 保存信息的文件的文件名为 appendonly.aof。在实际使用中,很少用到 AOF。

  • 如果要使用AOF,需要修改配置文件:appendonly yes,并重启 redis。

    appendonly no  # 默认不开启AOF模式
    appendfilename "appendonly.aof"  # 默认文件名
    

8.2.2、AOF 文件损坏

  • 如果 AOF 文件出错,此时 redis 是无法启动的,因此需要修改 AOF 文件。

  • redis 给我们提供了一个工具 redis-check-aof 来修复 AOF 文件:

    redis-check-aof --fix appendonly.aof
    
  • 如果文件正常,重启就可以直接恢复了。

8.2.3、优点和缺点

  • 优点

    1. 备份机制更稳健,丢失数据概率更低。
    2. AOF 文件是一个只进行追加的日志文件,所以不需要写入seek,可通过 redis-check-aof 工具修复
    3. AOF 文件具有可读性,可以很轻松的分析文件,也可以处理误操作。
  • 缺点

    1. 相对于数据文件来说,AOF 的文件体积远远大于 RDB,恢复备份速度比 RDB 慢!

    2. 根据所使用的 fsync 策略,AOF 的速度可能会慢于 RDB 。每次读写都同步的话,有一定的性能压力。

      # appendfsync always  # 每次修改都会 sync,消耗性能!
      appendfsync everysec  # 每秒执行一次 sync,可能会丢失这 1s 的数据!
      # appendfsync no  # 不执行 sync,这个时候操作系统自己同步数据,速度最快!
      
    3. AOF 都是 IO 操作,运行效率也要比 RDB 慢,因此 Redis 默认配置是 RDB 持久化。

8.2.4、AOF 重写

8.2.4.1、定义
  • AOF 采用文件追加方式,文件会越来越大为避免出现此种情况,新增了重写机制,当 AOF 文件的大小超过所设定的阈值时,Redis 就会启动 AOF 文件的内容压缩, 只保留可以恢复数据的最小指令集。可以使用命令 bgrewriteaof 手动触发。
8.2.4.2、作用
  1. 减少磁盘占用量
  2. 加速数据恢复
8.2.4.3、重写的触发
  1. bgrewrite命令:AOF 重写由 Redis 自行触发,bgrewriteaof 仅仅用于手动触发重写操作。
  2. 配置文件配置自动触发:AOF 重写自动触发机制,需要同时满足下面两个条件:
    • auto-aof-rewrite-min-size 64mb:触发 AOF 文件执行重写的最小尺寸
    • auto-aof-rewrite-percentage 100:触发 AOF 文件执行重写的增长率
    • 如上述配置,当 AOF 文件的体积大于 64Mb,并且 AOF 文件的体积比上一次重写之后的体积大了至少一倍(100%)时,Redis 将执行 bgrewriteaof 命令进行重写。
8.2.4.4、重写的执行逻辑
  1. bgrewriteaof触发重写,判断是否当前有bgsave或bgrewriteaof在运行,如果有,则等待该命令结束后再继续执行。
  2. 主进程fork出子进程执行重写操作,保证主进程不会阻塞。
  3. 子进程遍历redis内存中数据到临时文件,客户端的写请求同时写入aof_buf缓冲区和aof_rewrite_buf重写缓冲区保证原AOF文件完整以及新AOF文件生成期间的新的数据修改动作不会丢失。
    1. 子进程写完新的AOF文件后,向主进程发信号,父进程更新统计信息。
    2. 主进程把aof_rewrite_buf中的数据写入到新的AOF文件。
  4. 使用新的AOF文件覆盖旧的AOF文件,完成AOF重写。

image.png

8.3、RDB 和 AOF 选择

8.3.1、Redis 持久化

  1. RDB 持久化方式能够在指定的时间间隔内对你的数据进行快照存储
  2. AOF 持久化方式记录每次对服务器写的操作,当服务器重启的时候会重新执行这些命令来恢复原始的数据,AOF命令以Redis 协议追加保存每次写的操作到文件末尾,Redis还能对AOF文件进行后台重写,使得AOF文件的体积不至于过大。
  3. 只做缓存,如果你只希望你的数据在服务器运行的时候存在,你也可以不使用任何持久化
  4. 同时开启两种持久化方式:
    • 在这种情况下,当redis重启的时候会优先载入AOF文件来恢复原始的数据,因为在通常情况下AOF文件保存的数据集要比RDB文件保存的数据集要完整。
    • RDB 的数据不实时,同时使用两者时,服务器重启也只会找AOF文件,那要不要只使用AOF呢?建议不要,因为RDB更适合用于备份数据库(AOF在不断变化不好备份),快速重启,而且不会有AOF可能潜在的Bug,留着作为一个万一的手段。
  5. 性能建议
    • 因为RDB文件只用作后备用途,建议只在Slave上持久化RDB文件,而且只要15分钟备份一次就够了,只保留 save 900 1 这条规则。
    • 如果 Enable AOF,好处是在最恶劣情况下也只会丢失不超过两秒数据,启动脚本较简单只load自己的AOF文件就可以了,代价:一是带来了持续的IO,二是AOF rewrite 的最后将 rewrite 过程中产生的新数据写到新文件造成的阻塞几乎是不可避免的。只要硬盘许可,应该尽量减少AOF rewrite的频率,AOF重写的基础大小默认值64M太小了,可以设到5G以上,默认超过原大小100%大小重写可以改到适当的数值。
    • 如果不 Enable AOF,仅靠 Master-Slave Repllcation 实现高可用性也可以,能省掉一大笔IO,也减少了rewrite时带来的系统波动。代价:如果Master/Slave 同时倒掉,会丢失十几分钟的数据,启动脚本也要比较两个 Master/Slave 中的 RDB文件,载入较新的那个(微博就是这种架构)。

8.3.2、RDB 和 AOF 简单对比

RDBAOF
启动优先级
体积
恢复速度
数据安全性丢数据根据策略决定

8.3.3、RDB 和 AOF 详细对比

  • RDB的优点

    • RDB 是一个非常紧凑的文件,它保存了某个时间点得数据集,非常适用于数据集的备份,比如你可以在每个小时报保存一下过去24小时内的数据,同时每天保存过去30天的数据,这样即使出了问题你也可以根据需求恢复到不同版本的数据集。

    • RDB 是一个紧凑的单一文件,很方便传送到另一个远端数据中心或者亚马逊的 S3(可能加密),非常适用于灾难恢复。

    • RDB 在保存 RDB 文件时父进程唯一需要做的就是 fork 出一个子进程,接下来的工作全部由子进程来做,父进程不需要再做其他 IO 操作,所以 RDB 持久化方式可以最大化redis的性能。

    • 与 AOF 相比,在恢复大的数据集的时候,RDB 方式会更快一些。

  • RDB的缺点

    • 如果你希望在 redis 意外停止工作(例如电源中断)的情况下丢失的数据最少的话,那么 RDB 不适合你。虽然你可以配置不同的 save 时间点(例如每隔5分钟并且对数据集有100个写的操作),是 Redis 要完整的保存整个数据集是一个比较繁重的工作,你通常会每隔5分钟或者更久做一次完整的保存,万一在Redis 意外宕机,你可能会丢失几分钟的数据。

    • RDB 需要经常 fork 子进程来保存数据集到硬盘上,当数据集比较大的时候,fork 的过程是非常耗时的,可能会导致 Redis 在一些毫秒级内不能响应客户端的请求。如果数据集巨大并且 CPU 性能不是很好的情况下,这种情况会持续1秒,AOF 也需要 fork,但是你可以调节重写日志文件的频率来提高数据集的耐久度。

  • AOF 优点

    • 使用 AOF 会让你的 Redis 更加耐久,你可以使用不同的fsync策略:无fsync,每秒fsync,每次写的时候fsync。使用默认的每秒fsync策略,Redis的性能依然很好(fsync是由后台线程进行处理的,主线程会尽力处理客户端请求),一旦出现故障,你最多丢失1秒的数据。

    • AOF 文件是一个只进行追加的日志文件,所以不需要写入 seek,即使由于某些原因(磁盘空间已满,写的过程中宕机等等)未执行完整的写入命令,你也可使用 redis-check-aof 工具修复这些问题。

    • Redis 可以在 AOF 文件体积变得过大时,自动地在后台对 AOF 进行重写,重写后的新 AOF 文件包含了恢复当前数据集所需的最小命令集合。 整个重写操作是绝对安全的,因为 Redis 在创建新 AOF 文件的过程中,会继续将命令追加到现有的 AOF 文件里面,即使重写过程中发生停机,现有的 AOF 文件也不会丢失。 而一旦新 AOF 文件创建完毕,Redis 就会从旧 AOF 文件切换到新 AOF 文件,并开始对新 AOF 文件进行追加操作。

    • AOF 文件有序地保存了对数据库执行的所有写入操作,这些写入操作以 Redis 协议的格式保存,因此 AOF 文件的内容非常容易被人读懂,对文件进行分析(parse)也很轻松。导出(export)AOF 文件也非常简单:举个例子,如果你不小心执行了 FLUSHALL 命令,但只要 AOF 文件未被重写,那么只要停止服务器,移除 AOF 文件末尾的 FLUSHALL 命令,并重启 Redis,就可以将数据集恢复到 FLUSHALL 执行之前的状态。

  • AOF 缺点

    • 对于相同的数据集来说,AOF 文件的体积通常要大于 RDB 文件的体积。

    • 根据所使用的 fsync 策略,AOF 的速度可能会慢于 RDB 。 在一般情况下, 每秒 fsync 的性能依然非常高, 而关闭 fsync 可以让 AOF 的速度和 RDB 一样快, 即使在高负荷之下也是如此。 不过在处理巨大的写入载入时,RDB 可以提供更有保证的最大延迟时间(latency)。

8.3.3、如何选择使用哪种持久化方式?

  • 一般来说, 如果想达到足以媲美 PostgreSQL 的数据安全性, 你应该同时使用两种持久化功能。
  • 如果你非常关心你的数据, 但仍然可以承受数分钟以内的数据丢失, 那么你可以只使用 RDB 持久化。
  • 有很多用户都只使用 AOF 持久化, 但并不推荐这种方式: 因为定时生成 RDB 快照(snapshot)非常便于进行数据库备份, 并且 RDB 恢复数据集的速度也要比 AOF 恢复的速度要快。

9、Redis 订阅与发布

  • Redis 发布订阅(pub/sub)是一种消息通信模式:发送者(pub)发送消息,订阅者(sub)接收消息。微信、微博、关注系统!
  • Redis 客户端可以订阅任意数量的频道。

9.1、订阅/发布消息图

  • 订阅/发布消息图:第一个:消息发送者,第二个:频道,第三个:消息订阅者

  • 下图展示了频道 channel1,以及订阅这个频道的三个客户端 —— client2、client5 和 client1 之间的关系:

在这里插入图片描述

  • 当有新消息通过 PUBLISH 命令发送给频道 channel1 时,这个消息就会被发送给订阅它的三个客户端:

在这里插入图片描述

9.2、订阅/发布命令

命令描述
PSUBSCRIBE pattern [pattern..]订阅一个或多个符合给定模式的频道。
PUNSUBSCRIBE pattern [pattern..]退订一个或多个符合给定模式的频道。
PUBSUB subcommand [argument[argument]]查看订阅与发布系统状态。
PUBLISH channel message向指定频道发布消息
SUBSCRIBE channel [channel..]订阅给定的一个或多个频道。
SUBSCRIBE channel [channel..]退订一个或多个频道

9.3、测试示例

------------------消息订阅端----------------------
127.0.0.1:6379> subscribe chwlyn # 订阅chwlyn频道
Reading messages... (press Ctrl-C to quit) # 等待接收消息
1) "subscribe" # 订阅成功的消息
2) "chwlyn"
3) (integer) 1
1) "message" # 接收到来自chwlyn频道的消息 "hello,world!"
2) "chwlyn"
3) "hello,world!"
1) "message" # 接收到来自chwlyn频道的消息 "ding."
2) "chwlyn"
3) "ding."

------------------消息发布端----------------------
127.0.0.1:6379> publish chwlyn hello,world!
(integer) 1
127.0.0.1:6379> publish chwlyn ding.
(integer) 1
127.0.0.1:6379> 

-----------------查看活跃的频道--------------------
127.0.0.1:6379> pubsub channels
1) "chwlyn"

9.4、订阅/发布原理

  • Redis 是使用 C 实现的,可以通过分析 Redis 源码里的 pubsub.c 文件,了解发布和订阅机制的底层实现,加深对 Redis 的理解。
  • Redis 通过 PUBLISH、SUBSCRIBE 和 PSUBSCRIBE 等命令实现发布和订阅功能。
    • 通过 SUBSCRIBE 命令订阅某频道后,redis-server 里维护了一个字典,字典的键就是一个个频道,而字典的值则是一个链表,链表中保存了所有订阅这个 channel 的客户端。SUBSCRIBE 命令的关键,就是将客户端添加到给定 channel 的订阅链表中。
    • 通过 PUBLSH 命令向订阅者发送消息,redis-server 会使用给定的频道作为键,在它所维护的 channel 字典中查找记录了订阅这个频道的所有客户端的链表,遍历这个链表,将消息发布给所有订阅者。
    • Pub/Sub 从字面上理解就是发布(Publish)与订阅(Subscribe),在 Redis 中,你可以设定对某一个 key 值进行消息发布及消息订阅,当一个 key 值上进行了消息发布后,所有订阅它的客户端都会收到相应的消息。这一功能最明显的用法就是用作实时消息系统,比如普通的即时聊天、群聊等功能。
  • 每个 Redis 服务器进程都维持着一个表示服务器状态的 redis.h/redisServer 结构, 结构的 pubsub_channels 属性是一个字典, 这个字典就用于保存订阅频道的信息,其中,字典的键为正在被订阅的频道, 而字典的值则是一个链表, 链表中保存了所有订阅这个频道的客户端

在这里插入图片描述

  • 客户端订阅,就被链接到对应频道的链表的尾部,退订则就是将客户端节点从链表中移除。

9.5、应用场景

  1. 实时消息系统(消息订阅):公众号订阅,微博关注等(最早更多是使用消息队列来进行实现)
  2. 实时聊天:频道可以当做多人在线聊天室,将消息回显给所有人即可
  3. 订阅关注系统
  4. 稍微复杂的场景,我们就会使用消息中间件MQ处理。

9.6、缺点

  1. 如果一个客户端订阅了频道,但自己读取消息的速度却不够快的话,那么不断积压的消息会使redis输出缓冲区的体积变得越来越大,这可能使得redis本身的速度变慢,甚至直接崩溃。
  2. 这和数据传输可靠性有关,如果在订阅方断线,那么他将会丢失所有在短线期间发布者发布的消息。

10、Redis 主从复制

10.1、概述

10.1.1、什么是主从复制

  • **主从复制,是指将一台 Redis 服务器的数据,复制到其他的 Redis 服务器。**前者称为主节点(Master/Leader),后者称为从节点(Slave/Follower)。
  • 数据的复制是单向的!只能由主节点复制到从节点(主节点以写为主、从节点以读为主)。
  • 默认情况下,每台Redis服务器都是主节点,一个主节点可以有0个或者多个从节点,但每个从节点只能由一个主节点。

10.1.2、主从复制的作用

  1. 数据冗余:主从复制实现了数据的热备份,是持久化之外的一种数据冗余的方式。
  2. 故障恢复:当主节点故障时,从节点可以暂时替代主节点提供服务,实现快速的故障恢复,是一种服务冗余的方式。
  3. 负载均衡:在主从复制的基础上,配合读写分离,可以由主节点提供写服务,由从节点提供读服务(即写Redis数据时应用连接主节点,读Redis数据时应用连接从节点),分担服务器负载;尤其是在写少读多的场景下,通过多个从节点分担读负载,可以大大提高Redis服务器的并发量。
  4. 高可用基石:除了上述作用以外,主从复制还是哨兵和集群能够实施的基础,因此说主从复制是Redis高可用的基础。

10.1.3、为什么使用集群

  • 一般来说,要将Redis运用于工程项目中,只使用一台Redis是万万不能的(宕机),原因如下:

    1. 从结构上,单个Redis服务器会发生单点故障,并且一台服务器需要处理所有的请求负载,压力较大;
    2. 从容量上,单个Redis服务器内存容量有限,就算一台Redis服务器内存容量为256G,也不能将所有内存用作Redis存储内存,一般来说,单台Redis最大使用内存不应该超过20G。
  • 例如电商网站上的商品,一般都是一次上传,无数次浏览的,说专业点也就是“多读少写”。对于这种场景,一般可以使用如下这种架构,称作“一主三从”:

    figures\32、Redis(Redis主从复制)

  • 主从复制,读写分离!80% 的情况下都是在进行读操作!一主二从的架构经常使用,这可以减缓服务器的压力。在公司中,主从复制是必须要使用的,因为在真实的项目中不可能单机使用 Redis!

  • 简单来说,有以下三个原因:

    1. 单台服务器难以负载大量的请求;
    2. 单台服务器故障率高,系统崩坏概率大;
    3. 单台服务器内存容量有限。

10.2、集群环境搭建

10.2.1、基本环境配置

  • 只配置从库,不用配置主库!在 Redis.conf 配置文件中,注意到有一个 replication 模块。
  1. 启动一个服务,查看当前库的主从复制信息:
127.0.0.1:6379> info replication # 查看当前库的信息
# Replication
role:master # 角色:master
connected_slaves:0 # 从机数量:当前没有从机
master_failover_state:no-failover
master_replid:5c3d40b552d730b0d5ff57fe15aad9e74e8025f0
master_replid2:0000000000000000000000000000000000000000
master_repl_offset:0
second_repl_offset:-1
repl_backlog_active:0
repl_backlog_size:1048576
repl_backlog_first_byte_offset:0
repl_backlog_histlen:0
  1. 既然需要启动多个服务,那么就需要多个配置文件。复制三个配置文件,修改对应的信息:

    • 端口号:port 6379
    • pid文件名:pidflie /www/server/redis/redis_6379.pid
    • 日志文件名:logfile “/www/server/redis/redis_6379.log”
    • 备份文件名:dbfilename dump_6379.rdb
    [root@VM-4-12-centos ~]# cd /www/server/redis
    [root@VM-4-12-centos redis]# cp redis.conf myconfig/redis6379.conf
    [root@VM-4-12-centos redis]# cp redis.conf myconfig/redis6380.conf
    [root@VM-4-12-centos redis]# cp redis.conf myconfig/redis6381.conf
    [root@VM-4-12-centos redis]# cd myconfig
    [root@VM-4-12-centos myconfig]# ls
    redis6379.conf  redis6380.conf  redis6381.conf
    [root@VM-4-12-centos myconfig]# vim redis6379.conf
    [root@VM-4-12-centos myconfig]# vim redis6380.conf
    [root@VM-4-12-centos myconfig]# vim redis6381.conf
    
  2. 启动四个 Linux 连接(1 主、2 从、1 测试),用于开启单机多服务集群:

    [root@VM-4-12-centos src]# ./redis-server ../myconfig/redis6379.conf
    [root@VM-4-12-centos src]# ./redis-server ../myconfig/redis6380.conf
    [root@VM-4-12-centos src]# ./redis-server ../myconfig/redis6381.conf
    [root@VM-4-12-centos src]# ps -ef|grep redis
    root      1727     1  0 18:12 ?        00:00:00 ./redis-server *:6379
    root      2864     1  0 18:12 ?        00:00:00 ./redis-server *:6380
    root      3427     1  0 18:12 ?        00:00:00 ./redis-server *:6381
    root      4114 11002  0 18:13 pts/3    00:00:00 grep --color=auto redis
    

10.2.2、一主二从配置

  • 默认情况下,每台 Redis 服务器都是主节点;一般情况下只需要配置从机!在这里,我们对集群进行如下配置:一主(79)二从(80,81)。

  • 使用 SLAVEOF host port 为从机配置主机。配置完成后,两台从机都显示连接到主机,但是主机显示连接到的从机数量为 0:

    [root@VM-4-12-centos src]# ./redis-cli -p 6380
    127.0.0.1:6380> auth xxxxxx
    OK
    127.0.0.1:6380> slaveof 127.0.0.1 6379 # 配置主机
    OK
    127.0.0.1:6380> info replication
    # Replication
    role:slave # 当前角色是从机
    master_host:127.0.0.1 # 主机信息
    master_port:6379
    master_link_status:down
    master_last_io_seconds_ago:-1
    master_sync_in_progress:0
    slave_read_repl_offset:1
    slave_repl_offset:1
    master_link_down_since_seconds:-1
    slave_priority:100
    slave_read_only:1
    replica_announced:1
    connected_slaves:0
    master_failover_state:no-failover
    master_replid:166d778584a9203796205ff4d1dc5001cd69c0c4
    master_replid2:0000000000000000000000000000000000000000
    master_repl_offset:0
    second_repl_offset:-1
    repl_backlog_active:0
    repl_backlog_size:1048576
    repl_backlog_first_byte_offset:0
    repl_backlog_histlen:0
    
    [root@VM-4-12-centos src]# ./redis-cli -p 6381
    127.0.0.1:6381> auth xxxxxx
    OK
    127.0.0.1:6381> slaveof 127.0.0.1 6379 #配置主机
    OK
    127.0.0.1:6381> info replication
    # Replication
    role:slave # 当前角色是从机
    master_host:127.0.0.1 # 主机信息
    master_port:6379
    master_link_status:down
    master_last_io_seconds_ago:-1
    master_sync_in_progress:0
    slave_read_repl_offset:1
    slave_repl_offset:1
    master_link_down_since_seconds:-1
    slave_priority:100
    slave_read_only:1
    replica_announced:1
    connected_slaves:0
    master_failover_state:no-failover
    master_replid:3565a21bb00fce7005456676a783e654c612cb0d
    master_replid2:0000000000000000000000000000000000000000
    master_repl_offset:0
    second_repl_offset:-1
    repl_backlog_active:0
    repl_backlog_size:1048576
    repl_backlog_first_byte_offset:0
    repl_backlog_histlen:0
    
    [root@VM-4-12-centos src]# ./redis-cli -p 6379
    127.0.0.1:6379> auth xxxxxx
    OK
    127.0.0.1:6379> info replication
    # Replication
    role:master # 当前角色是主机
    connected_slaves:0 # 连接从机的数量
    master_failover_state:no-failover
    master_replid:d0ce0bacb986217bfeb7ea79c8ba288d0b2a989f
    master_replid2:0000000000000000000000000000000000000000
    master_repl_offset:0
    second_repl_offset:-1
    repl_backlog_active:0
    repl_backlog_size:1048576
    repl_backlog_first_byte_offset:0
    repl_backlog_histlen:0
    
  • 查看从机log日志文件发现错误信息,发现主机master要求密码验证:

    MASTER aborted replication with an error: NOAUTH Authentication required.
    
  • 对于 Redis 集群,如果设置了 requirepass,则一定要在从机的配置文件中设置 masterauth,否则从节点无法正常工作。

    127.0.0.1:6379> info replication
    # Replication
    role:master # 当前角色是主机
    connected_slaves:2  # 连接从机的数量变为2个
    slave0:ip=127.0.0.1,port=6380,state=online,offset=126,lag=0 # 从机0的配置
    slave1:ip=127.0.0.1,port=6381,state=online,offset=126,lag=1 # 从机1的配置
    master_failover_state:no-failover
    master_replid:bef0bb203fb9076d4c7edba33764fd5ebc3a0ecc
    master_replid2:0000000000000000000000000000000000000000
    master_repl_offset:126
    second_repl_offset:-1
    repl_backlog_active:1
    repl_backlog_size:1048576
    repl_backlog_first_byte_offset:1
    repl_backlog_histlen:126
    
  • 这里是使用命令搭建,是暂时的!真实开发中应该在从机的配置文件中进行配置,这样的话是永久的。

    ################################# REPLICATION #################################
    
    # Master-Replica replication. Use replicaof to make a Redis instance a copy of
    # another Redis server. A few things to understand ASAP about Redis replication.
    #
    #   +------------------+      +---------------+
    #   |      Master      | ---> |    Replica    |
    #   | (receive writes) |      |  (exact copy) |
    #   +------------------+      +---------------+
    #
    # 1) Redis replication is asynchronous, but you can configure a master to
    #    stop accepting writes if it appears to be not connected with at least
    #    a given number of replicas.
    # 2) Redis replicas are able to perform a partial resynchronization with the
    #    master if the replication link is lost for a relatively small amount of
    #    time. You may want to configure the replication backlog size (see the next
    #    sections of this file) with a sensible value depending on your needs.
    # 3) Replication is automatic and does not need user intervention. After a
    #    network partition replicas automatically try to reconnect to masters
    #    and resynchronize with them.
    #
    # replicaof <masterip> <masterport> # 配置主机信息
    
    # If the master is password protected (using the "requirepass" configuration
    # directive below) it is possible to tell the replica to authenticate before
    # starting the replication synchronization process, otherwise the master will
    # refuse the replica request.
    #
    # masterauth <master-password> #若主机需要密码验证,配置主机密码
    

10.3、主从复制流程

10.4、使用规则

  1. 从机只能读不能写,主机可读可写但是多用于写。

    127.0.0.1:6380> set name cwlin # 从机6380写入失败
    (error) READONLY You can't write against a read only replica.
    
    127.0.0.1:6381> set name cwlin # 从机6381写入失败
    (error) READONLY You can't write against a read only replica.
    
    127.0.0.1:6379> set name cwlin # 主机6379写入成功
    OK
    127.0.0.1:6379> get name # 主机6379读取成功
    "cwlin"
    
    127.0.0.1:6380> get name # 从机6380读取成功
    "cwlin"
    
    127.0.0.1:6381> keys * # 从机6381读取成功
    1) "name"
    
  2. 主机断电宕机后,默认情况下从机的角色不会发生变化,集群中只是失去了写操作,当主机恢复以后,又会连接上从机恢复原状。

  3. 从机断电宕机后,**若不是使用配置文件配置从机,即使用命令行,那么再次启动后作为主机是无法获取之前主机的数据的。**若此时重新配置称为从机,又可以获取到主机的所有数据。这里就要提到一个同步原理(详见 10.5)。

  4. 第 2 条中提到,默认情况下,主机故障后,不会出现新的主机,有三种方式可以产生新的主机:

    • 从机手动执行命令 slaveof no one,这样执行以后从机会独立出来成为一个主机,其他节点就可以手动重新连接到新的主节点;
    • 层层链路:上一个 Master 连接下一个 Slave,这时候也可以完成我们的主从复制;
    • 使用哨兵模式,自动选举(详见第 11 节)。

    image-20201105122218386

10.5、复制原理

  • slave 启动成功连接到 master 后会发送一个sync同步命令;Master 接到命令,启动后台的存盘进程,同时收集所有接收到的用于修改数据集命令,在后台进程执行完毕之后,master 将传送整个数据文件到 slave,并完成一次完全同步。
    • 全量复制:slave 服务在接收到数据库文件数据后,将其存盘并加载到内存中。
    • 增量复制:master 继续将新的所有收集到的修改命令依次传给 slave,完成同步。
  • 但是,只要是重新连接 master,一次完全同步(全量复制)将被自动执行!
  • 因此,我们的数据一定可以在从机中看到!

11、哨兵模式(面试重点)

11.1、概述

  • 主从切换技术的方法是:当主服务器宕机后,需要手动把一台从服务器切换为主服务器,这就需要人工干预,费事费力,还会造成一段时间内服务不可用。这不是一种推荐的方式,更多时候,我们优先考虑哨兵模式。Redis 从 2.8 开始正式提供了 Sentinel(哨兵) 架构来解决这个问题。能够后台监控主机是否故障,如果故障了根据投票数自动将从库转换为主库。
  • 哨兵模式是一种特殊的模式,首先Redis提供了哨兵的命令,哨兵是一个独立的进程,作为进程,它会独立运行。其原理是哨兵通过发送命令,等待Redis服务器响应,从而监控运行的多个Redis实例。

11.1.1、单机单个哨兵

img

  • 哨兵的作用:
    • 通过发送命令,让Redis服务器返回监控其运行状态,包括主服务器和从服务器。
    • 当哨兵监测到master宕机,会自动将slave切换成master,然后通过发布订阅模式通知其他的从服务器,修改配置文件,让它们切换主机。
  • 然而,一个哨兵进程对 Redis 服务器进行监控,可能会出现问题。为此,我们可以使用多个哨兵进行监控,各个哨兵之间还会进行监控,这样就形成了多哨兵模式

11.1.2、多哨兵模式

img

  • 用文字描述一下**故障切换(failover)**的过程:
    • 假设主服务器宕机,哨兵1先检测到这个结果,系统并不会马上进行 failover 过程,仅仅是哨兵1主观的认为主服务器不可用,这个现象成为主观下线
    • 当后面的哨兵也检测到主服务器不可用,并且数量达到一定值时,那么哨兵之间就会进行一次投票,投票的结果由一个哨兵发起,进行 failover 操作。切换成功后,就会通过发布订阅模式,让各个哨兵把自己监控的从服务器实现切换主机,这个过程称为客观下线
  • 这样对于客户端而言,一切都是透明的。

11.2、配置哨兵

  1. 在 myconfig 文件夹下,配置哨兵配置文件 sentinel.conf:

    [root@VM-4-12-centos myconfig]# ls
    redis6379.conf  redis6380.conf  redis6381.conf
    [root@VM-4-12-centos myconfig]# vim sentinel.conf
    
    # sentinel monitor 被监控的名称 host port 1
    # 最后一位 1:当一个哨兵主观认为主机断开,就可以客观认为主机故障,然后开始选举新的主机
    sentinel monitor mymaster 127.0.0.1 6379 1
    
    # 连接master的密码
    sentinel auth-pass mymaster chwlyn199809
    protected-mode no
    
  2. 启动哨兵模式:

    [root@VM-4-12-centos src]# ./redis-sentinel ../myconfig/sentinel.conf
    9099:X 24 Jan 2022 21:52:20.053 # oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo
    9099:X 24 Jan 2022 21:52:20.053 # Redis version=6.2.6, bits=64, commit=00000000, modified=0, pid=9099, just started
    9099:X 24 Jan 2022 21:52:20.053 # Configuration loaded
    9099:X 24 Jan 2022 21:52:20.053 * monotonic clock: POSIX clock_gettime
                    _._                                                  
               _.-``__ ''-._                                             
          _.-``    `.  `_.  ''-._           Redis 6.2.6 (00000000/0) 64 bit
      .-`` .-```.  ```\/    _.,_ ''-._                                  
     (    '      ,       .-`  | `,    )     Running in sentinel mode
     |`-._`-...-` __...-.``-._|'` _.-'|     Port: 26379
     |    `-._   `._    /     _.-'    |     PID: 9099
      `-._    `-._  `-./  _.-'    _.-'                                   
     |`-._`-._    `-.__.-'    _.-'_.-'|                                  
     |    `-._`-._        _.-'_.-'    |           https://redis.io       
      `-._    `-._`-.__.-'_.-'    _.-'                                   
     |`-._`-._    `-.__.-'    _.-'_.-'|                                  
     |    `-._`-._        _.-'_.-'    |                                  
      `-._    `-._`-.__.-'_.-'    _.-'                                   
          `-._    `-.__.-'    _.-'                                       
              `-._        _.-'                                           
                  `-.__.-'                                               
    
    9099:X 24 Jan 2022 21:52:20.060 # Sentinel ID is a7f156e1e4140e5693632d1f5fe7ff208e2c9796
    9099:X 24 Jan 2022 21:52:20.060 # +monitor master mymaster 127.0.0.1 6379 quorum 1
    9099:X 24 Jan 2022 21:52:20.061 * +slave slave 127.0.0.1:6380 127.0.0.1 6380 @ mymaster 127.0.0.1 6379
    9099:X 24 Jan 2022 21:52:20.066 * +slave slave 127.0.0.1:6381 127.0.0.1 6381 @ mymaster 127.0.0.1 6379
    
  3. 此时,哨兵监视着主机 6379。如果我们断开主机,那么当一个哨兵认为主机断开时,将自动选取新的主机,原先的主机也被加入从机中。

    9099:X 24 Jan 2022 21:54:09.038 # +sdown master mymaster 127.0.0.1 6379
    9099:X 24 Jan 2022 21:54:09.038 # +odown master mymaster 127.0.0.1 6379 #quorum 1/1 # 一个哨兵认为主机断开
    9099:X 24 Jan 2022 21:54:09.038 # +new-epoch 1
    9099:X 24 Jan 2022 21:54:09.038 # +try-failover master mymaster 127.0.0.1 6379
    9099:X 24 Jan 2022 21:54:09.044 # +vote-for-leader a7f156e1e4140e5693632d1f5fe7ff208e2c9796 1
    9099:X 24 Jan 2022 21:54:09.044 # +elected-leader master mymaster 127.0.0.1 6379
    9099:X 24 Jan 2022 21:54:09.044 # +failover-state-select-slave master mymaster 127.0.0.1 6379
    9099:X 24 Jan 2022 21:54:09.134 # +selected-slave slave 127.0.0.1:6380 127.0.0.1 6380 @ mymaster 127.0.0.1 6379
    9099:X 24 Jan 2022 21:54:09.134 * +failover-state-send-slaveof-noone slave 127.0.0.1:6380 127.0.0.1 6380 @ mymaster 127.0.0.1 6379
    9099:X 24 Jan 2022 21:54:09.192 * +failover-state-wait-promotion slave 127.0.0.1:6380 127.0.0.1 6380 @ mymaster 127.0.0.1 6379
    9099:X 24 Jan 2022 21:54:09.290 # +promoted-slave slave 127.0.0.1:6380 127.0.0.1 6380 @ mymaster 127.0.0.1 6379
    9099:X 24 Jan 2022 21:54:09.290 # +failover-state-reconf-slaves master mymaster 127.0.0.1 6379
    9099:X 24 Jan 2022 21:54:09.385 * +slave-reconf-sent slave 127.0.0.1:6381 127.0.0.1 6381 @ mymaster 127.0.0.1 6379
    9099:X 24 Jan 2022 21:54:10.298 * +slave-reconf-inprog slave 127.0.0.1:6381 127.0.0.1 6381 @ mymaster 127.0.0.1 6379
    9099:X 24 Jan 2022 21:54:10.298 * +slave-reconf-done slave 127.0.0.1:6381 127.0.0.1 6381 @ mymaster 127.0.0.1 6379
    9099:X 24 Jan 2022 21:54:10.353 # +failover-end master mymaster 127.0.0.1 6379
    9099:X 24 Jan 2022 21:54:10.353 # +switch-master mymaster 127.0.0.1 6379 127.0.0.1 6380 # 自动选取新的主机
    9099:X 24 Jan 2022 21:54:10.353 * +slave slave 127.0.0.1:6381 127.0.0.1 6381 @ mymaster 127.0.0.1 6380
    9099:X 24 Jan 2022 21:54:10.353 * +slave slave 127.0.0.1:6379 127.0.0.1 6379 @ mymaster 127.0.0.1 6380 # 原先的主机也被加入从机中
    9099:X 24 Jan 2022 21:54:40.379 # +sdown slave 127.0.0.1:6379 127.0.0.1 6379 @ mymaster 127.0.0.1 6380
    
  4. 若此时再次打开主机,那么原主机将成为新主机的从机,归并到新的主机下,这就是哨兵模式的规则!

    9099:X 24 Jan 2022 21:59:58.771 # -sdown slave 127.0.0.1:6379 127.0.0.1 6379 @ mymaster 127.0.0.1 6380
    9099:X 24 Jan 2022 22:00:08.765 * +convert-to-slave slave 127.0.0.1:6379 127.0.0.1 6379 @ mymaster 127.0.0.1 6380
    

11.3、哨兵模式的优缺点

  • 优点:
    1. 哨兵集群,基于主从复制模式,所有主从复制的优点,它都有
    2. 主从可以切换,故障可以转移,系统的可用性更好
    3. 哨兵模式是主从模式的升级,手动到自动,更加健壮
  • 缺点:
    1. Redis不好在线扩容,集群容量一旦达到上限,在线扩容就十分麻烦
    2. 实现哨兵模式的配置其实是很麻烦的,里面有很多配置项

11.4、哨兵模式的全部配置

完整的哨兵模式配置文件 sentinel.conf

# Example sentinel.conf
 
# 哨兵sentinel实例运行的端口 默认26379
port 26379
 
# 哨兵sentinel的工作目录
dir /tmp
 
# 哨兵sentinel监控的redis主节点的 ip port 
# master-name  可以自己命名的主节点名字 只能由字母A-z、数字0-9 、这三个字符".-_"组成。
# quorum 当这些quorum个数sentinel哨兵认为master主节点失联 那么这时 客观上认为主节点失联了
# sentinel monitor <master-name> <ip> <redis-port> <quorum>
sentinel monitor mymaster 127.0.0.1 6379 1
 
# 当在Redis实例中开启了requirepass foobared 授权密码 这样所有连接Redis实例的客户端都要提供密码
# 设置哨兵sentinel 连接主从的密码 注意必须为主从设置一样的验证密码
# sentinel auth-pass <master-name> <password>
sentinel auth-pass mymaster MySUPER--secret-0123passw0rd
 
 
# 指定多少毫秒之后 主节点没有应答哨兵sentinel 此时 哨兵主观上认为主节点下线 默认30秒
# sentinel down-after-milliseconds <master-name> <milliseconds>
sentinel down-after-milliseconds mymaster 30000
 
# 这个配置项指定了在发生failover主备切换时最多可以有多少个slave同时对新的master进行 同步,
这个数字越小,完成failover所需的时间就越长,
但是如果这个数字越大,就意味着越 多的slave因为replication而不可用。
可以通过将这个值设为 1 来保证每次只有一个slave 处于不能处理命令请求的状态。
# sentinel parallel-syncs <master-name> <numslaves>
sentinel parallel-syncs mymaster 1
 
 
 
# 故障转移的超时时间 failover-timeout 可以用在以下这些方面: 
#1. 同一个sentinel对同一个master两次failover之间的间隔时间。
#2. 当一个slave从一个错误的master那里同步数据开始计算时间。直到slave被纠正为向正确的master那里同步数据时。
#3.当想要取消一个正在进行的failover所需要的时间。  
#4.当进行failover时,配置所有slaves指向新的master所需的最大时间。不过,即使过了这个超时,slaves依然会被正确配置为指向master,但是就不按parallel-syncs所配置的规则来了
# 默认三分钟
# sentinel failover-timeout <master-name> <milliseconds>
sentinel failover-timeout mymaster 180000
 
# SCRIPTS EXECUTION
 
#配置当某一事件发生时所需要执行的脚本,可以通过脚本来通知管理员,例如当系统运行不正常时发邮件通知相关人员。
#对于脚本的运行结果有以下规则:
#若脚本执行后返回1,那么该脚本稍后将会被再次执行,重复次数目前默认为10
#若脚本执行后返回2,或者比2更高的一个返回值,脚本将不会重复执行。
#如果脚本在执行过程中由于收到系统中断信号被终止了,则同返回值为1时的行为相同。
#一个脚本的最大执行时间为60s,如果超过这个时间,脚本将会被一个SIGKILL信号终止,之后重新执行。
 
#通知型脚本:当sentinel有任何警告级别的事件发生时(比如说redis实例的主观失效和客观失效等等),将会去调用这个脚本,
#这时这个脚本应该通过邮件,SMS等方式去通知系统管理员关于系统不正常运行的信息。调用该脚本时,将传给脚本两个参数,
#一个是事件的类型,
#一个是事件的描述。
#如果sentinel.conf配置文件中配置了这个脚本路径,那么必须保证这个脚本存在于这个路径,并且是可执行的,否则sentinel无法正常启动成功。
#通知脚本
# sentinel notification-script <master-name> <script-path>
  sentinel notification-script mymaster /var/redis/notify.sh
 
# 客户端重新配置主节点参数脚本
# 当一个master由于failover而发生改变时,这个脚本将会被调用,通知相关的客户端关于master地址已经发生改变的信息。
# 以下参数将会在调用脚本时传给脚本:
# <master-name> <role> <state> <from-ip> <from-port> <to-ip> <to-port>
# 目前<state>总是“failover”,
# <role>是“leader”或者“observer”中的一个。 
# 参数 from-ip, from-port, to-ip, to-port是用来和旧的master和新的master(即旧的slave)通信的
# 这个脚本应该是通用的,能被多次调用,不是针对性的。
# sentinel client-reconfig-script <master-name> <script-path>
sentinel client-reconfig-script mymaster /var/redis/reconfig.sh

12、缓存穿透与雪崩(面试高频)

12.1、缓存穿透(查不到)

12.1.1、概念

  • 在默认情况下,用户请求数据时,会先在缓存(Redis)中查找,若没找到即缓存未命中,再在数据库中进行查找,数量少可能问题不大,可是一旦大量的请求数据(例如秒杀场景)缓存都没有命中的话,就会全部转移到数据库上,造成数据库极大的压力,就有可能导致数据库崩溃。网络安全中也有人恶意使用这种手段进行攻击被称为洪水攻击。

在这里插入图片描述

  • 简单的说,穿透是一个数据查不到导致的。

12.1.2、解决方案

布隆过滤器(重点)

  • 布隆过滤器是一种数据结构,对所有可能查询的参数以Hash的形式存储,以便快速确定是否存在这个值,在控制层先进行拦截校验,校验不通过直接打回,减轻了存储系统的压力。

在这里插入图片描述

缓存空对象

  • 一次请求若在缓存和数据库中都没找到,就在缓存中放一个空对象用于处理后续这个请求。
  • 当存储层不命中后,即使返回的空对象也将其缓存起来,同时会设置一个过期时间,之后再访问这个数据将会从缓存中获取,保护了后端数据源。

在这里插入图片描述

  • 但是这种方法会存在两个问题:
    1. 如果空值能够被缓存起来,这就意味着缓存需要更多的空间存储更多的键,因为这当中可能会有很多的空值的键;大量的空对象会耗费一定的空间,存储效率并不高。解决这个缺陷的方式就是设置较短过期时间。
    2. 即使对空值设置了过期时间,还是会存在缓存层和存储层的数据会有一段时间窗口的不一致,这对于需要保持一致性的业务会有影响。

12.2、缓存击穿(查太多,量太大,缓存过期)

12.2.1、概念

  • 相较于缓存穿透,缓存击穿的目的性更强,一个存在的key,在缓存过期的一刻,同时有大量的请求,这些请求都会击穿到DB,造成瞬时DB请求量大、压力骤增。这就是缓存被击穿,只是针对其中某个key的缓存不可用而导致击穿,但是其他的key依然可以使用缓存响应。
  • 比如热搜排行榜上,一个热点新闻被同时大量访问就可能导致缓存击穿。

在这里插入图片描述

  • 简单的说,穿透是一个数据找的人过多导致的。

12.2.2、解决方案

设置热点数据永不过期

  • 从缓存层面来看,没有设置过期时间,这样就不会出现热点数据过期的情况;
  • 但是,当Redis内存空间满的时候也会清理部分数据,而且此种方案会占用空间,一旦热点数据多了起来,就会占用部分空间。

加互斥锁(分布式锁)

  • 分布式锁:使用分布式锁,保证对于每个key同时只有一个线程去查询后端服务,其他线程没有获得分布式锁的权限,因此只需要等待即可。这种方式将高并发的压力转移到了分布式锁,因此对分布式锁考验很大;
  • 在访问key之前,采用SETNX(set if not exists)来设置另一个短期key来锁住当前key的访问,访问结束再删除该短期key。保证同时刻只有一个线程访问,这样对锁的要求就十分高。

12.3、缓存雪崩

12.3.1、概念

  • 大量的key设置了相同的过期时间,或者 Redis 服务器宕机,导致在缓存在同一时刻全部失效,造成瞬时DB请求量大、压力骤增,引起雪崩。
  • 缓存雪崩,是指在某一个时间段,缓存集中过期失效,Redis 宕机!

在这里插入图片描述

  • 产生雪崩的原因之一,比如在写本文的时候,马上就要到双十二零点,很快就会迎来一波抢购,这波商品时间比较集中的放入了缓存,假设缓存一个小时。那么到了凌晨一点钟的时候,这批商品的缓存就都过期了。而对这批商品的访问查询,都落到了数据库上,对于数据库而言,就会产生周期性的压力波峰。于是所有的请求都会达到存储层,存储层的调用量会暴增,造成存储层也会挂掉的情况。

在这里插入图片描述

  • 其实集中过期,倒不是非常致命,比较致命的缓存雪崩,是缓存服务器某个节点宕机或断网。因为自然形成的缓存雪崩,一定是在某个时间段集中创建缓存,这个时候,数据库也是可以顶住压力的。无非就是对数据库产生周期性的压力而已。而缓存服务节点的宕机,对数据库服务器造成的压力是不可预知的,很有可能瞬间就把数据库压垮。

12.3.2、解决方案

redis高可用

  • 这个思想的含义是,既然 redis 有可能挂掉,那我多增设几台 redis,这样一台挂掉之后其他的还可以继续工作,其实就是搭建的集群。

限流降级

  • 这个解决方案的思想是,在缓存失效后,通过加锁或者队列来控制读数据库写缓存的线程数量。比如对某个 key 只允许一个线程查询数据和写缓存,其他线程等待。

数据预热

  • 数据加热的含义就是在正式部署之前,我先把可能的数据先预先访问一遍,这样部分可能大量访问的数据就会加载到缓存中。在即将发生大并发访问前手动触发加载缓存不同的 key,设置不同的过期时间,让缓存失效的时间点尽量均匀。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值