0%

Redis汇总

NoSQL

技术的分类

  • 解决功能性的问题:Java、Jsp、RDBMS、Tomcat、HTML、Linux、JDBC、SVN
  • 解决扩展性的问题:Struts、Spring、SpringMVC、Hibernate、MyBatis
  • 解决性能的问题:NoSQL、Java线程、Hadoop、Nginx、MQ、ElasticSearch

多服务器问题

session存在哪?

  1. 存在cookie里;不安全,且网络负担效率低
  2. 存在文件服务器或数据库里;大量的IO效率问题
  3. session复制;session数据冗余,节点越多,浪费越大
  4. 缓存数据库;完成在内存中,速度快,数据结构简单

解决IO压力

添加缓存数据库,减少IO的读操作

打破了传统关系型数据库以业务逻辑为依据的存储模式,而针对不同数据结构类型改为以性能最优先的存储方式。

NoSQL概述

NoSQL(NoSQL=Not Only SQL),意即“不仅仅是SQL”,泛指非关系型数据库

特点:

  • 不遵循SQL标准
  • 不支持ACID
  • 远超于SQL的性能

适用场景:

  • 对数据高并发的读写
  • 海量数据的读写
  • 对数据高可扩展性的

不适用场景:

  • 需要事务支持的
  • 基于SQL结构化查询存储,处理复杂的关系

Redis6概述

  • Redis是一个开源的key-value存储系统
  • 支持的存储类型包括:string(字符串)、list(链表)、set(集合)、zset(sorted set,有序集合)和hash(哈希类型)
  • 这些数据类型都支持push/pop、add/remove及取交集并集及更丰富的操作,且这些操作都是原子性
  • Redis支持各种不同方式的排序
  • Redis数据缓存在内存
  • Redis会周期性的把更新的数据写入磁盘或把修改操作写入追加的记录文件
  • 在此基础上实现了master-slave(主从)同步

应用场景

  • 配合关系型数据库做高速缓存
    • 高频次、热门访问的数据,降低数据库IO
    • 分布式架构,做session共享
  • 多样的数据结构存储持久化数据
    • 最新N个数据------->通过List实现自然时间排序的数据
    • 排行榜,Top N------->利用zset(有序集合)
    • 时效性数据如手机验证码------->Expire过期
    • 计数器,秒杀------->原子性,自增方法INCR、DECR
    • 去除大量数据中的重复数据------->利用set集合
    • 构建队列------->利用list集合
    • 发布订阅消息系统------->pub/sub模式

安装

1
2
3
curl -fsSL https://packages.redis.io/gpg | sudo gpg --dearmor -o /usr/share/keyrings/redis-archive-keyring.gpg
sudo apt-get update
sudo apt-get install redis

安装目录

  • redis-benchmark:性能测试工具
  • redis-check-aof:修复有问题的AOF文件
  • redis-check-dump:修复有问题的dump.rdb文件
  • redis-sentinel:Redis集群使用
  • redis-server:Redis服务器启动命令
  • redis-cli:客户端,操作入口

启动

前台启动(不推荐)

1
redis-server

后台启动(推荐)

  1. 备份配置文件

    1
    sudo cp /etc/redis/redis.conf redis.conf.bak
  2. 修改配置文件中的daemonize,如果为no则改为yes

  3. 启动redis

    1
    sudo /etc/init.d/redis-server start
  4. 客户端访问测试

    1
    redis-cli

其它

  • Redis默认16个数据库,下标从0开始,默认使用0号库
  • 使用select <dbid>切换数据库,如:select 8
  • 所有库使用同样密码
  • 使用dbsize查看当前数据库的key的数量
  • flushdb清空当前库
  • flushall通杀全部库

Redis是单线程+多路IO复用技术

五大数据类型

相关命令

  • keys *:查看当前库所有key
  • exists key:判断某个key是否存在
  • type key:查看key是什么类型
  • del key:删除指定的key数据
  • unlink key:根据key选择非阻塞删除,仅将key从keyspace元数据中删除,真正的删除会在后续异步操作
  • expire key t :为给定的key设置过期时间为t
  • ttl key:查看还有多少秒过期,-1表示永不过期,-2表示已经过期
  • select <dbid>:切换数据库
  • dbsize:查看当前数据库的key的数量
  • flushdb:清空当前数据库
  • flushall:清空全部库

字符串(String)

常用命令

  • set <key> <value>:向数据库中添加数据
  • get <key>:查询对应键值
  • append <key> <value>:将给定value追加到原值的末尾
  • strlen <key>:获取值的长度
  • setnx <key> <value>:只有在key不存在时,设置key的值
  • incr <key>:将key中储存的数字值增1,只能对数字值操作,如果为空,新增值为1
  • decr <key>:将key中储存的数字值减1,只能对数字值操作,如果为空,新增值为-1
  • incrby <key> <步长>:将key中储存的数字值增长,自定义步长
  • decrby <key> <步长>:将key中储存的数字值减少,自定义步长

注:incr <key>:对存储在指定key的数字值执行原子的加1操作

所谓原子操作指的是不会被线程调度机制打断的操作

这种操作一旦开始,就一起运行到结束,中间不会有任何context switch(切换到另一个线程)

  1. 在单线程中,能够在单条指令中完成的操作都可以认为是原子操作,因为中断只能发生于指令之间
  2. 在多线程中,不能被其它进程(线程)打断的操作就叫原子操作
  • mset <key1> <value1> <key2> <value2>...:同时设置一个或多个key-value对

  • mget <key1> <key2> ...:同时获取一个或多个value

  • msetnx <key1> <value1> <key2> <value2>...:同时设置一个或多个key-value对,当且仅当所有给定key都不存在时

  • getrange <key> <起始位置> <结束位置>:获取值的范围,类似java中的substring,前包括,后包括,即范围是[起始,结束]

  • setrange <key> <起始位置> <value>:用value覆写key所储存的字符串值,从起始位置开始(索引从0开始)

  • setex <key> <过期时间> <value>:设置键值的同时,设置过期时间,单位秒

  • getset <key> <value>:以新换旧,设置了新值同时获取得旧值

数据结构

  • String的数据结构为简单动态字符串(Simple Dynamic String,缩写SDS)。是可以修改的字符串,内部结构实现上类似于Java的ArrayList,采用预先分配冗余空间的方式来减少内存的频繁分配
  • 当字符串长度小于1M时,扩容都是加倍现有的空间,如果超过1M,扩容时一次只会多扩1M的空间,需要注意的是字符串大小最大长度为512M

列表(List)

常用命令

  • lpush/rpush <key><value1><value2><value3>...:从左边/右边插入一个或多个值
  • lpop/rpop <key>:从左边/右边弹出一个值,值在键在,值无键无
  • rpoplpush <key1><key2>:从key1列表右边弹出一个值,插入到key2列表左边
  • lrange <key> <start> <stop>:按照索引下标获得元素(从左到右),-1表示右边第一个
  • lindex <key> <index>:按照索引下标获取元素(从左到右)
  • llen <key>:获得列表长度
  • linsert <key> before/after <value> <newvalue>:在value前面/后面插入newvalue
  • lrem <key> <n> <value>:从左边删除n个value(从左到右)
  • lset <key> <index> <value>:将列表key下标为index的值替换成value

数据结构

  • List的数据结构是快速链表quickList
  • 首先在列表元素较少的情况下会使用一块连续的内存存储,这个结构是ziplist,即压缩列表,将所有的元素紧挨着一起存储,分配的是一块连续的内存
  • 当数据量较多时才会改成quickList
  • 因为普通的链表需要的附加指针空间太大,会比较浪费空间。如这个列表里存的只是int类型的数据,结构上还需要两个额外的指针prev和next
  • Redis将链表和ziplist结合起来组成了quicklist,也就是将多个ziplist使用双向指针串起来使用。这样既满足了快速的插入删除性能,又不会出现太大的空间冗余

集合(Set)

常用命令

  • sadd <key> <value1> <value2> ...:将一个或多个元素加入到集合key中,已经存在的元素将被忽略
  • smember <key>:取出该集合的所有值
  • sismember <key> <value>:判断集合key是否含有该value值,有1,没有0
  • scard <key> <value>:返回该集合的元素个数
  • srem <key> <value1> <value2>...:删除集合中的某个元素
  • spop <key>:随机从该集合中弹出一个值
  • srandmember <key> <n>:随机从该集合中取出n个值,不会从集合中删除
  • smove <source> <dest> value:把集合中的一个值从source集合移动到dest集合
  • sinter <key1> <key2>:返回两个集合的交集元素
  • sunion <key1> <key2>:返回两个集合的并集元素
  • sdiff <key1> <key2>:返回两个集合的差集元素(key1中的,不包含key2中的)

数据结构

  • Set数据结构是dict字典,字典是用哈希表实现的
  • Redis的set结构的内部也使用hash结构,所有的value都指向同一个内部值

哈希(Hash)

简介

hash存储对象结构的三种方式:

  1. key:用户ID;value:序列化的value对象
  2. key:用户ID+标签;value:标签对应数据
  3. key:用户ID;Hash:field(标签),value(标签对应数据)

常用命令

  • hset <key> <field> <value>:给key集合中的field键赋值value
  • hget <key1> <field>:从key1集合field取出value
  • hmset <key1> <field1> <value1> <field2> <value2> ...:批量设置hash的值,现由hset代替
  • hexists <key1> <field>:查看哈希表key中,给定域field是否存在
  • hkeys <key>:列出该hash集合的所有field
  • hvals <key>:列出该hash集合的所有value
  • hincrby <key> <field> <increment>:为哈希表key中的域field的值加上增量1
  • hsetnx <key> <field> <value>:将哈希表key中的域field的值设置为value,当且仅当域field不存在

数据结构

  • Hash类型对应的数据结构是两种:ziplist(压缩列表),hashtable(哈希表)
  • 当field-value长度较短且个数较少时,使用ziplist,否则使用hashtable

有序集合Zset

常用命令

  • zadd <key> <score1> <value1> <score2> <value2>...:将一个或多个member元素及其score值加入到有序集key中
  • zrange <key> <start> <stop> [withscores]:返回有序集key中,下标在start和stop之间的元素,带withscores,可以让分数一起和值返回到结果集
  • zrangebyscore key min max [withscores] [limit offset count]:返回有序集key中,所有score值介于min和max之间(包括等于min和max)的成员。有序集成员按score值递增(从小到大)次序排列
  • zrevrangebyscore key max min [withscores] [limit offset count]:同上,改为从大到小排序
  • zincrby <key> <increment> <value>:为元素的score加上增量
  • zrem <key> <value>:删除该集合下,指定值的元素
  • zcount <key> <min> <max>:统计该集合分数区间内的元素个数
  • zrank <key> <value>:返回该值在集合中的排名,从0开始

数据结构

  • SortedSet(zset)是Redis提供的一个非常特别的数据结构,一方面它等价于Java的数据结构Map<String, Double>,可以给每个元素value赋予一个权重score,另一方面它又类似于TreeSet,内部的元素会按照权重score进行排序,可以得到每个元素的名次,还可以通过score的范围来获取元素的列表。
  • zset底层使用了两个数据结构:
    1. hash,hash的作用就是关联元素value和权重score,保障元素value的唯一性,可以通过元素value找到相应的score值
    2. 跳跃表,跳跃表的目的在于给元素value排序,根据score的范围获取元素列表

Redis6配置文件常用配置详解

1、Units 单位

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# Redis configuration file example.
#
# Note that in order to read the configuration file, Redis must be
# started with the file path as first argument:
#
# ./redis-server /path/to/redis.conf

# 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.

配置大小单位,开头定义了一些基本的度量单位,只支持bytes,不支持bit,大小写不敏感

2、INCLUDES包含

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
################################## 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

类似于C、C++中的include,多实例的情况可以把公用的配置文件提取出来

3、网络相关配置

3.1、bind

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
################################## 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 ::1
  • 默认情况下bind=127.0.0.1只能接受本机的访问请求
  • 不写的情况下,无限制接受任何ip地址的访问
  • 生产环境肯定要写应用服务器的地址;服务器需要远程访问,所以需要将其注释掉
  • 如果开启了protected-mode,则在没有设定bind ip且没有设密码的情况下,Redis只允许接受本机的响应

3.2、protected-mode

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# 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 yes
  • 本机访问保护模式,默认为yes,表示本机能访问而远程不能访问

3.3、 Port

1
2
3
# 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
  • 端口号,默认是6379

3.4、tcp-backlog

1
2
3
4
5
6
7
8
9

# TCP listen() backlog.
#
# 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
  • 设置tcp的backlog,backlog其实是一个连接队列,backlog队列总和=未完成三次握手队列+已经完成三次握手队列
  • 在高并发环境下需要一个高backlog值来避免慢客户端连接问题
  • 注意Linux内核会将这个值减小到/proc/sys/net/core/somaxconn的值(128),所以需要确认增大/proc/sys/net/core/somaxconn和/proc/sys/net/ipv4/tcp_max_syn_backlog(128)两个值来达到想要的效果

3.5、timeout

1
2
3
4
5
6
7
8
9
10
11
# Unix socket.
#
# 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 /var/run/redis/redis-server.sock
# unixsocketperm 700

# Close the connection after a client is idle for N seconds (0 to disable)
timeout 0
  • 一个空闲的客户端维持多少秒会关闭,0表示关闭该功能。即永不关闭

3.6 tcp-keepalive

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 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
  • 对访问客户端的一种心跳检测,每隔n秒检测一次
  • 单位为秒,如果设置为0,则不会进行Keepalive检测,建议设置成60

4、GENERAL通用

4.1、daemonize

1
2
3
4
5
################################# 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
  • 是否为守护进程

4.2、pidfile

1
2
3
4
5
6
7
8
9
10
# 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 /var/run/redis/redis-server.pid
  • 存放pid文件的位置,每个实例会产生一个不同的pid文件

4.3、loglevel

1
2
3
4
5
6
7
# 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
  • 指定日志记录级别,Redis总共支持四个级别:debug、verbose、notice、warning,默认是notice
  • 四个级别根据使用阶段来选择,生产环境选择notice或warning

4.4、logfile

1
2
3
4
5
6
7
8
9
10
11
12
13
# 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 /var/log/redis/redis-server.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
  • 日志文件名称

4.5、databases 16

1
2
3
4
# 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
  • 设定库的数量,默认为16,默认数据库为0,可以使用select <dbid>命令在连接上指定数据库id

5、SECURITY安全

5.1、设置密码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
################################## 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 foobared
  • 访问密码的查看、设置和取消
  • 可通过命令设置密码,但这样只是临时的,重启redis服务器就会还原
    • config get requirepass
    • config set requirepass <password>
    • auth <password>
  • 永久设置需要在配置文件中配置

6、CLIENTS

6.1、maxclients

1
2
3
4
5
6
7
8
9
10
# 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
  • 设置redis同时可以与多少客户端进行连接
  • 默认情况下为10000个客户端
  • 如果达到了此限制,redis会拒绝新的连接请求,并且向这些连接请求方发出"max number of clients reached"作为回应

7、MEMORY MANAGEMENT

7.1、maxmemory

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
############################## 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>

  • 建议必须设置,否则,将内存占满,造成服务器宕机
  • 设置redis可以使用的内存量,一旦达到内存使用上限,redis会试图移除内部数据,移除规则可以通过maxmemory-policy来指定
  • 如果redis无法根据移除规则来移除内存中的数据,或者设置了“不允许移除”,则redis会针对那些需要申请内存的指令来返回错误信息,如:SET、LPUSH等
  • 但对于无内存申请的指令,仍然会正常响应,如GET等。如果redis是主redis(说明有从redis),则在设置内存使用上限时,需要在系统中留出一些内存空间给同步队列缓存,只有在设置的是”不移除“的情况下,才不用考虑这个因素

7.2、maxmemory-policy

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# 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
  • volatile-lru:使用LRU算法移除key,只对设置了过期时间的键
  • allkeys-lru:在所有集合key中,使用LRU算法移除key
  • volatile-lfu:在过期集合中移除随机的key,只对设置了过期时间的键
  • allkeys-lfu:在所有集合key中,移除随机的key
  • volatile-ttl:移除那些TTL值最小的key,即那些最近要过期的key
  • noeviction:不进行移除,针对写操作,只是返回错误信息

7.3、maxmemory-samples

1
2
3
4
5
6
7
8
9
10

# 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
  • 设置样本数量,LRU算法和最小TTL算法都并非是精确的算法,而是估算值,所以可以设置样本的大小,redis默认会检查这么多个key并选择其中LRU的那个
  • 一般设置3到7的数字,数值越小样本越不准确,但性能消耗越小

Redis6的发布与订阅

什么是发布和订阅

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

Redis的发布和订阅

  • 客户端可以订阅频道如图:

  • 当给这个频道发布消息后,消息就会发送给订阅的客户端

发布订阅相关命令

  • subscribe <channel>:订阅channel
  • publish <channel> <message>:给频道channel发送消息message,返回值是订阅者数量

Jedis操作Redis6

1、导包

1
2
3
4
5
6
<!-- https://mvnrepository.com/artifact/redis.clients/jedis -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>4.2.3</version>
</dependency>

2、使用

注:连接前需要先修改配置文件并且放开6379端口

1
2
3
4
5
Jedis jedis = new Jedis("192.168.1.27", 6379);  // 传入IP和端口号
// 测试
String value = jedis.ping();
System.out.println(value);
jedis.close();

Jedis常用API

Key

  • jedis.set("k1", "v1")
  • jedis.keys("*")
  • jedis.exists("k1")
  • jedis.ttl("k1")
  • jedis.get("k1")

String

  • jedis.mset("str1","v1","str2","v2")
  • jedis.mget("str1","str2")

List

  • jedis.lrange("mylist", 0, -1)

Set

  • jedis.sadd("orders", "order01")
  • jedis.smembers("orders")
  • jedis.srem("orders", "order01")

Hash

  • jedis.hset("hash1", "userName", "Tom")
  • jedis.hget("hash1", "userName")
  • jedis.hmset("hash2", new HashMap<String, String>())
  • jedis.hmget("hash2", "telphone", "email")

zset

  • jedis.zadd("zset01", 100d, "z3")
  • jedis.zrange("zset01", 0, -1)

SpringBoot整合Redis

1、导入依赖

1
2
3
4
5
6
7
8
9
10
11
12
<!-- redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

<!-- spring2.X集成redis所需common-pool2-->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
<version>2.11.1</version>
</dependency>

2、配置application.properties

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#Redis服务器地址
spring.redis.host=192.168.140.136
#Redis服务器连接端口
spring.redis.port=6379
#Redis数据库索引(默认为0)
spring.redis.database= 0
#连接超时时间(毫秒)
spring.redis.timeout=1800000
#连接池最大连接数(使用负值表示没有限制)
spring.redis.lettuce.pool.max-active=20
#最大阻塞等待时间(负数表示没限制)
spring.redis.lettuce.pool.max-wait=-1
#连接池中的最大空闲连接
spring.redis.lettuce.pool.max-idle=5
#连接池中的最小空闲连接
spring.redis.lettuce.pool.min-idle=0

3、添加Redis配置类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
@EnableCaching
@Configuration
public class RedisConfig extends CachingConfigurerSupport {

@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
RedisSerializer<String> redisSerializer = new StringRedisSerializer();
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
template.setConnectionFactory(factory);
//key序列化方式
template.setKeySerializer(redisSerializer);
//value序列化
template.setValueSerializer(jackson2JsonRedisSerializer);
//value hashmap序列化
template.setHashValueSerializer(jackson2JsonRedisSerializer);
return template;
}

@Bean
public CacheManager cacheManager(RedisConnectionFactory factory) {
RedisSerializer<String> redisSerializer = new StringRedisSerializer();
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
//解决查询缓存转换异常的问题
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
// 配置序列化(解决乱码的问题),过期时间600秒
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofSeconds(600))
.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))
.disableCachingNullValues();
RedisCacheManager cacheManager = RedisCacheManager.builder(factory)
.cacheDefaults(config)
.build();
return cacheManager;
}
}

Redis6的事务操作

  • Redis事务是一个单独的隔离操作:事务中的所有命令都会序列化、按顺序地执行。事务在执行过程中,不会被其它客户端发送来的命令请求所打断
  • Redis事务的主要作用就是串联多个命令防止别的命令插队

multi、exec、discard

  • 从输入Multi命令开始,输入的命令都会依次进入命令队列中,但不会执行,直到输入Exec后,Redis会将之前的命令队列中的命令依次执行
  • 组队的过程中可以通过discard来放弃组队

事务的错误处理

  • 组队中某个命令出了报告错误,执行时整个队列都会被取消
  • 如果执行阶段某个命令出现错误,则只有报错的命令不会被执行,而其它命令都会执行,不会回滚

Redis锁相关命令

  • watch key [key ...]:在执行multi之前执行,可以监视一个(或多个)key,如果在事务执行之前这个(或这些)key被其它命令所改动,则事务会被打断
  • unwatch:取消watch命令对所有key的监视,如果在执行watch之后,exec命令或discard命令先被执行,则不需要再执行unwatch

Redis事务三特性

  • 单独的隔离操作
    • 事务中的所有命令都会序列化,按顺序地执行。事务在执行的过程中不会被其它客户端发送来的命令请求所打断
  • 没有隔离级别的概念
    • 队列中的命令没有提交之前都不会实际被执行,因为事务提交前任何指令都不会被实际执行
  • 不保证原子性
    • 事务中如果有一条命令执行失败,其后的命令仍然会被执行,没有回滚

Redis事务秒杀案例

模拟秒杀的工具

  1. 安装

    1
    sudo apt install apache2-utils
  2. 测试

    1
    2
    3
    4
    5
    ab -n 1000 -c 100 http://127.0.0.1:8080/secKill
    # -n:表示当前请求次数是
    # -c:表示当前并发次数是
    # -T:如果使用POST/PUT请求时需要设置content-type
    # -p:postfile,即post请求对应参数信息所存放的文件

业务实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
@Service
public class ProductServiceImpl implements ProductService {
@Autowired
private RedisTemplate redisTemplate;
@Override
public boolean doSecKill(String uid, String productId) {
// 1. uid和productId非空判断
if (uid == null || productId == null) return false;
// 2. 连接redis
// 3. 拼接key
// 3.1 库存key
String kcKey = "sk:" + productId + ":qt";
// 3.2 秒杀成功用户key
String userKey = "sk:" + productId + ":user";
// 4. 获取库存,如果库存null,表示还没开始
// 监视库存
List result = (List) redisTemplate.execute(new SessionCallback<List<Object>>() {
public List<Object> execute(RedisOperations operations) throws DataAccessException {
operations.watch(kcKey);
Integer kc = (Integer) operations.opsForValue().get(kcKey);
if (kc == null) {
System.out.println("秒杀还没有开始");
return null;
}
// 5. 判断用户是否重复秒杀操作
if (operations.opsForSet().isMember(userKey, uid)) {
System.out.println("已经秒杀成功了,不能重复秒杀!");
return null;
}
// 6. 判断如果库存数量小于1,秒杀结束
if (kc < 1) {
System.out.println("秒杀已经结束了");
return null;
}
operations.multi();
// 7. 秒杀操作
// 7.1 库存-1
operations.opsForValue().decrement(kcKey);
// 7.2 用户设置到清单
operations.opsForSet().add(userKey, uid);
return operations.exec();
}
});
// System.out.println(result);
if(result == null || result.size() == 0) return false;
System.out.println("秒杀成功");
return true;
}
}

使用Lua解决库存遗留问题

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
@Service
public class ProductServiceImpl implements ProductService {
@Autowired
private RedisTemplate redisTemplate;

@Override
public boolean doSecKill(String uid, String productId) {
DefaultRedisScript redisScript = new DefaultRedisScript();
redisScript.setResultType(String.class);
redisScript.setScriptSource(new ResourceScriptSource(new ClassPathResource("secKill.lua")));
Integer result = (Integer) redisTemplate.execute(redisScript, Arrays.asList(uid, productId));

switch (result) {
case 0:
System.out.println("已抢空!");
return false;
case 1:
System.out.println("抢购成功");
break;
case 2:
System.out.println("该用户已抢过");
return false;
default:
System.out.println("抢购异常");
return false;
}
return true;
}
}

lua脚本

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
local userid=KEYS[1];
local prodid=KEYS[2];
local qtkey="sk:"..prodid..":qt";
local usersKey="sk:"..prodid..":user";
local userExists=redis.call("sismember",usersKey,userid);
if tonumber(userExists)==1 then
return "2";
end
local num= redis.call("get" ,qtkey);
if tonumber(num)<=0 then
return "0";
else
redis.call("decr",qtkey);
redis.call("sadd",usersKey,userid);
end
return "1";

Redis6持久化

RDB(Redis DataBase)

是什么

  • 指定的时间间隔内将内存中的数据集快照写入磁盘,也就是Snapshot快照,恢复时将快照文件读取到内存中

如何执行

  • Redis会单独创建(fork)一个子进程来进行持久化,会先将数据写入到一个临时文件中,待持久化过程结束了,再用这个临时文件替换上次持久化好的文件。整个过程中,主进程不进行任何IO操作,这就确保了极高的性能。如果需要进行大规模数据的恢复,且对于数据恢复的完整性不是非常敏感,则RDB要比AOF方式更加的高效。
  • RDB的缺点是:最后一次持久化后的数据可能丢失

Fork

  • Fork的作用是复制一个目标与当前进程一样的进程,新进程的所有数据(变量、环境变量、程序计数器等)数值都会原进程一致,但是一个全新的进程,并作为原进程的子进程
  • 在Linux程序中,fork()会产生一个和父进程一样的子进程,但子进程在此后多会exec系统调用,出于效率考虑,Linux引入了"写时复制技术"
  • 一般情况父进程和子进程会共用同一段物理内存,只有进程空间的各段的内容要发生变化时,都会将父进程的内容复制一份给子进程

相关配置

dbfilename

  • 设置持久化文件名称
1
2
# The filename where to dump the DB
dbfilename dump.rdb

dir

  • 设置持久化文件路径
1
2
3
4
5
6
7
8
9
# 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 /var/lib/redis

快照触发机制

  1. 配置文件中默认配置
  2. 命令save/bgsave
    1. save:只管保存,其它不管,全部阻塞。手动保存,不建议
    2. bgsave:Redis会在后台异步进行快照操作,快照同时还可以响应客户端请求
      • lastsave:获取最后一次成功执行快照的时间
  3. flushall也会触发快照,产生空的dump.rdb文件

SNAPSHOTTING:快照

save

  • 默认是:
    • 900秒(15分钟)内有至少一个key变化了
    • 300秒(5分钟)内有至少10个key变化了
    • 60秒内有至少10000个key变化了
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
################################ 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
save 300 10
save 60 10000

stop-writes-on-bgsave-error

  • 当Redis无法写入磁盘的话,直接关掉Redis的写操作,默认yes,推荐yes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 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

rdbcompression

  • 对于存储到磁盘中的快照,可以设置是否进行压缩存储。如果是的话,redis会采用LZF算法进行压缩。
  • 如果不想消耗CPU来进行压缩的话,可以设置为关闭此功能。推荐yes.
1
2
3
4
5
# 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

rdbchecksum

  • 在存储快照后,可以让redis使用CRC64算法进行数据校验
  • 但这样会增加约10%的性能消耗,如果希望获得最大的性能提升可以关闭
  • 推荐yes
1
2
3
4
5
6
7
8
# 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

备份与恢复

备份

  1. 通过配置文件查看rdb文件位置
  2. 将rdb文件拷贝到其它地方

恢复

  1. 关闭Redis
  2. 将备份文件拷贝到工作目录下
  3. 启动Redis,备份数据会直接加载

RDB优劣势

优势:

  • 适合大规模的数据恢复
  • 对数据完整性和一致性要求不高时更适合使用
  • 节省磁盘空间
  • 恢复速度快

劣势:

  • Fork时,内存中的数据被克隆一份,大致2倍的膨胀性需要考虑
  • 虽然Redis在fork时使用了写时复制技术,但如果数据庞大时还是比较消耗性能
  • 一定时间间隔做一次备份,所以如果Redis意外宕掉就会丢失最后一次快照后的所有修改

如何停止使用RDB

  • redis-cli config set save "":动态停止RDB,save后面给空值,表示禁用保存策略

AOF(Append Of File)

是什么

  • 以日志的形式来记录每个写操作(增量保存),将Redis执行过的所有写指令记录下来(读操作不记录),只许追加文件,但不改写文件,Redis启动之初会读取该文件重新构建数据,换言之,Redis重启的话就根据日志文件内容将写指令从前到后执行一次以完成数据恢复工作。

如何执行

  1. 客户端的请求写命令会被追加到AOF缓冲区
  2. AOF缓冲区根据AOF持久化策略(always/everysec/no)将操作同步到磁盘的AOF文件
  3. AOF文件大小超过重写策略或手动重写时,会对AOF文件rewrite重写,压缩AOF文件容量
  4. Redis服务重启时,会重新加载AOF文件中的写操作达到数据恢复的目的

appendonly:开启AOF

  • AOF默认是不开启的,需要在配置文件中配置appendonly yes
  • 可以在redis.conf中配置文件名称,默认是:appendfilename "appendonly.aof"
  • AOF文件的保存路径与RDB的路径一致
  • 如果AOF和RDB同时开启,Redis默认取AOF的数据
1
2
3
4
5
6
7
8
9
10
11
12
13
# 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"

appendfsync:同步频率

  • always:表示始终同步,每次Redis的写入都会立刻记入日志,性能较差但数据完整性好
  • everysec:每秒同步,每秒记入日志一次,如果宕机,本秒的数据可能丢失
  • no:不主动进行同步,将同步时间交操作系统
1
2
3
4
5
6
7
8
9
10
11
12
# 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

Rewrite压缩

是什么

  • AOF采用文件追加方式,文件会越来越大为避免出现此种情况,新增了重写机制, 当AOF文件的大小超过所设定的阈值时,Redis就会启动AOF文件的内容压缩, 只保留可以恢复数据的最小指令集.可以使用命令bgrewriteaof

原理

  • AOF文件持续增长而过大时,会fork出一条新进程来将文件重写(也是先写临时文件最后再rename),redis4.0版本后的重写,是指上就是把rdb 的快照,以二进制的形式附在新的aof头部,作为已有的历史数据,替换掉原来的流水账操作
  • no-appendfsync-on-rewrite
    • 如果 no-appendfsync-on-rewrite=yes ,不写入aof文件只写入缓存,用户请求不会阻塞,但是在这段时间如果宕机会丢失这段时间的缓存数据。(降低数据安全性,提高性能)
    • 如果 no-appendfsync-on-rewrite=no, 还是会把数据往磁盘里刷,但是遇到重写操作,可能会发生阻塞。(数据安全,但是性能降低)

触发机制

  • Redis会记录上次重写时的AOF大小,默认配置是当AOF文件大小是上次rewrite后大小的一倍且文件大于64M时触发
  • 重写虽然可以节约大量磁盘空间,减少恢复时间。但是每次重写还是有一定的负担的,因此设定Redis要满足一定条件才会进行重写
  • auto-aof-rewrite-percentage:设置重写的基准值,文件达到100%时开始重写(文件是原来重写后文件的2倍时触发)
  • auto-aof-rewrite-min-size:设置重写的基准值,最小文件64MB。达到这个值开始重写。
  • 如果Redis的**AOF当前大小>= base_size +base_size*100% (默认)且当前大小>=64mb(默认)的情况下**,Redis会对AOF进行重写。

重写流程

  1. bgrewriteaof触发重写,判断是否当前有bgsavebgrewriteaof在运行,如果有,则等待该命令结束后再继续执行
  2. 主进程fork出子进程执行重写操作,保证主进程不会阻塞
  3. 子进程遍历redis内存中数据到临时文件,客户端的写请求同时写入aof_buf缓冲区和aof_rewrite_buf重写缓冲区保证原AOF文件完整以及新AOF文件生成期间的新的数据修改动作不会丢失
  4. 子进程写完新的AOF文件后,向主进程发信号,父进程更新统计信息;主进程把aof_rewrite_buf中的数据写入到新的AOF文件
  5. 使用新的AOF文件覆盖旧的AOF文件,完成AOF重写

AOF备份与恢复

  • AOF的备份机制和性能虽然和RDB不同, 但是备份和恢复的操作同RDB一样,都是拷贝备份文件,需要恢复时再拷贝到Redis工作目录下,启动系统即加载。
  • 正常恢复:
    • 修改默认的appendonly no,改为yes
    • 将有数据的aof文件复制到对应目录
    • 重启redis重新加载
  • 异常恢复:
    • 修改默认的appendonly no,改为yes
    • 如遇到AOF文件操作,通过redis-check-aof --fix appendonly.aof进行恢复
    • 备份被写坏的AOF文件
    • 重启redis重新加载

优劣势

优势:

  • 备份机制更稳健,丢失数据概率更低
  • 可读的日志文本,通过操作AOF文件,可以处理误操作

劣势:

  • 比起RDB占用更多的磁盘空间
  • 恢复备份速度慢
  • 每次读写都同步的话有一定的性能压力
  • 存在个别bug,造成不能恢复

如何选择

  • 官方推荐两个都启用
  • 如果对数据不敏感,可以选单独用RDB。
  • 不建议单独用 AOF,因为可能会出现Bug。
  • 如果只是做纯内存缓存,可以都不用。

Redis6的主从复制

  • 主从复制是指主机数据更新后根据配置和策略,自动同步到备机的master/slave机制Master以写为主,Slave以读为主
  • 作用:
    • 读写分离,性能扩展
    • 容灾快速恢复

案例

  1. 假设有三个redis服务器:

    • redis6379.conf

      1
      2
      3
      4
      include /myredis/redis.conf
      pidfile /var/run/redis_6379.pid
      port 6379
      dbfilename dump6379.rdb
    • redis6380.conf

      1
      2
      3
      4
      include /myredis/redis.conf
      pidfile /var/run/redis_6380.pid
      port 6380
      dbfilename dump6380.rdb
    • redis6381.conf

      1
      2
      3
      4
      include /myredis/redis.conf
      pidfile /var/run/redis_6381.pid
      port 6381
      dbfilename dump6381.rdb
  2. 启动三台redis服务器

  3. 查看系统进程检查启动情况

  4. 在redis-cli中通过info replication查看主从复制相关信息

  5. 配置从库(配从不配主)

    1. 通过slaveof <ip> <port>分别配置从服务器6380和6381,具体命令为:slaveof 127.0.0.1 6379
    2. 测试,在主机上写,可以在从机上读到对应的数据
    3. 如果主机挂掉,则重启即可
    4. 如果从机挂掉,则需要重新设置:slaveof 127.0.0.1 6379,也可以将其添加到配置文件使其永久有效

常用的三种方式

1. 一主二仆

2. 薪火相传

  • 上一个slave可以是下一个slave的master,slave同样可以接收其它slave的连接和同步请求,可以有效减轻原master的写压力,去中心化降低风险

方式:slaveof <ip> <port>

问题:

  • 中途若变更转向,会清除之前的数据,重新建立最新的
  • 一旦某个slave宕机,后面的slave都无法备份
  • 主机挂了,从机还是从机,无法写数据了

3. 反客为主

  • 当一个master宕机后,后面的slave可以立刻升为master,其后面的slave不用做任何修改
  • 方法:通过命令slaveof no one,将对应从机变为主机

复制原理

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

哨兵模式(sentinel)

  • 哨兵模式是常用的三种方式中的反客为主的自动版,能够后台监控主机是否故障,如果故障了根据投票数自动将从库转换为主库

使用步骤(案例)

  1. 仍然以三个服务为例,分别是6379(主机),6380(从机),6381(从机)
  2. 自定义的redis目录下建立sentinel.conf文件
  3. 配置哨兵:在配置文件中添加sentinel monitor mymaster 127.0.0.1 6379 1,其中mymaster为监控对象起的服务器名称,1表示至少有1个哨兵同意迁移
  4. 启动哨兵,对应命令:redis-sentinel myredis/sentinel.conf
  5. 当主机挂掉时,会从从机中选举产生新的主机,选举标准是根据优先级别(slave-priority),而原来的主机如果再重启恢复,则会再变成从机

复制延时

  • 由于所有的写操作都是先在master上操作,然后同步更新到slave上,所以从master同步到slave机器有一定的延时,当系统很繁忙时,延迟问题会更加严重,slave机器数量的增加也会使得这个问题更加严重

故障恢复

  • 优先级在redis.conf中默认:slave-priority 100,值越小优先级越高
  • 偏移量最大是指获得原主机数据最全的
  • 每个redis实例启动后都会随机产生一个40位的runid

Redis6集群

简介

集群要解决的问题:

容量不够时,Redis如何扩容?

并发写操作时,Redis如何分摊?

此外,主从复制各种模式下主机宕机导致IP地址发生变化,应用程序中配置需求修改对应的主机地址、端口等信息。

针对这些,Redis3.0提供了解决方案,就是无中心化集群配置:

  • 相当于每个主机都是代理主机,都能作为集群入口

什么是Redis集群?

  • Redis集群实现了对Redis的水平扩容,即启动N个Redis节点,将整个数据库分布存储在N个节点中,每个节点存储总数据的1/N

  • Redis集群通过分区(partion)来提供一定程度的可用性(availability),即使集群中有一部分节点失效或无法通讯,集群也可以继续处理命令请求。

案例

以6个主机为例,3主3从,假设对应的是:192.168.1.2,192.168.1.3,192.168.1.4,192.168.1.5,192.168.1.6,192.168.1.7

1、配置基本信息

开启daemonize yes

Pid文件名字

指定端口

Log文件名字

Dump.rdb名字

Appendonly 关掉或者换名字

2、redis cluster配置修改

1
2
3
4
5
6
7
8
9
include /home/bigdata/redis.conf
port 6379
pidfile "/var/run/redis_6379.pid"
dbfilename "dump6379.rdb"
dir "/home/zephon/redis_cluster"
logfile "/home/zephon/redis_cluster/redis_err_6379.log"
cluster-enabled yes # 打开集群模式
cluster-config-file nodes-6379.conf # 设定节点配置文件名
cluster-node-timeout 15000 # 设定节点失联时间,超过该时间(毫秒),集群自动进行主从切换

注:需要将修改好的redis.conf复制到不同主机上

3、启动6个主机的服务

1
redis-server redis.conf

4、将6个节点合成一个集群

组合之前要确保所有redis服务已启动,nodes-xxx.conf文件生成正常

1
redis-cli --cluster create --cluster --replicas 1 192.168.1.2:6379 192.168.1.3:6379 192.168.1.4:6379 192.168.1.5:6379 192.168.1.6:6379 192.168.1.7:6379

需要注意的是,这里的IP需要用真实IP,不能用127.0.0.1

--replicas 1:表示采用最简单的方式配置集群,一台主机一台从机,正好三组

5、集群策略连接

1
redis-cli -c -p 6379
  • 通过-c采用集群策略连接,设置数据会自动切换到相应的写主机

6、查看集群信息

1
cluster nodes

集群节点分配

  • 一个集群至少要有三个主节点
  • 选项--cluster-replicas 1表示希望为集群中的每个主节点创建一个从节点
  • 分配原则尽量保证每个主数据库运行在不同的IP地址,每个从库和主库不在一个IP地址

slots

  • 一个Redis集群包含16384个插槽(hash slot),数据库中的每个键都属于这16384个插槽的其中一个
  • 集群使用公式CRC16(key)%16384来计算键key属于哪个槽,其中CRC16(key)用于计算key的CRC16校验和
  • 集群中的每个节点负责处理一部分插槽。

集群中值的录入与查询

录入

  • 在redis-cli每次录入、查询键值,redis都会计算出该key应该送往的插槽,如果不是该客户端对应服务器的插槽,redis会报错,并告知前往的redis实例地址和端口
  • redis-cli客户端提供了-c参数实现自动重定向
    • redis-cli -c -p 6379登入后,再录入、查询键值对可以自动重定向
  • 不在一个slot下的键值,是不能使用mget、mset等多键操作
  • 可以通过{}来定义组的概念,从而使key中{}内相同内容的键值对放到一个slot中去
    • 如:mset name{user} v1 age{user} v2 address{user} v3

查询

  • cluster getkeysinslot <slot> <count>:返回count个slot槽中的键
  • cluster keyslot <group>:返回{group}中对应组的slot槽
  • cluster countkeysinslot <slot>:返回slot槽中键的数量

故障恢复

  • 如果某一段插槽的主从都挂掉,而cluster-require-full-coverage为yes,则整个集群都挂掉
  • 如果某一段插槽的主从都挂掉,而cluster-require-full-coverage为no,则插槽数据全部不能使用,也无法存储

Redis集群的优劣

优势:

  • 实现扩容
  • 分摊压力
  • 无中心配置相对简单

劣势:

  • 多键操作不被支持
  • 多键的Redis事务不被支持,lua脚本不被支持
  • 由于Redis集群方案出现较晚,很多公司已经用了其它集群方案,而代理或客户端分片的方案想迁移到redis cluster,需要整体迁移而不是逐步过渡,复杂度较大

Redis6应用问题解决

缓存穿透

问题描述

key对应的数据在数据源并不存在,每次针对key的请求从缓存中获取不到,请求都会压到数据源,从而可能压垮数据源。如用一个不存在的用户id获取用户信息,无论缓存还是数据库都没有,若黑客利用此漏洞攻击可能压垮数据库。

解决方案

一个一定不存在缓存及查询不到的数据,由于缓存是不命中时被动写的,并且出于容错考虑,如果从存储层查不到数据则不写入缓存,这将导致这个不存在的数据每次请求都要到存储层去查询,失去了缓存意义。

解决方案:

  1. 对空值缓存:如果一个查询返回的数据为空(不管数据是否不存在),都将这个空结果(null)进行缓存,设置空结果的过期时间会很短,最长不超过五分钟

  2. 设置可访问的名单(白名单):使用bitmaps类型定义一个可访问的名单,名单id作为bitmaps的偏移量,每次访问和bitmap里面的id进行比较,如果访问id不在bitmaps里面,进行拦截,不允许访问

  3. 采用布隆过滤器:布隆过滤器(Bloom Filter)是1970年由布隆提出的。实际上是一个很长的二进制向量(位图)和一系列随机映射函数(哈希函数)。可以用于检索一个元素是否在一个集合中。它的优点是空间效率和查询时间都远远超过一般算法,缺点是有一定的误识别率和删除困难。

    将所有可能存在的数据哈希到一个足够大的Bitmaps中,一个一定不存在的数据会被这个bitmaps拦截掉,从而避免了对底层存储系统的查询压力

  4. 进行实时监控:当发现redis的命中率开始急速降低,需要排查访问对象和访问的数据,和运维人员配合,可以设置黑名单限制服务

缓存击穿

问题描述

key对应的数据存在,但在redis中过期,此时若有大量并发请求过来,这些请求发现缓存过期一般都会从后端DB加载数据并设回到缓存,这个时候大并发的请求可能会瞬间把后端DB压垮。

解决方案

key可能会在某些时间点被超高并发地访问,是一种非常"热点"的数据。这个时候需要考虑一个问题:缓存被“击穿”的问题

解决问题:

  1. 预先设置热门数据:在redis高峰访问之前,把一些热门数据提前存入到redis里面,加大这些热门数据key的时长
  2. 实时调整:现场监控哪些数据热门,实时调整key的过期时长
  3. 使用锁
    1. 在缓存失效的时候(判断拿出来的值为空),不是立即去load db
    2. 而是先使用缓存工具的某些带成功操作返回值的操作(如redis的setnx)去set一个mutex key
    3. 当操作返回成功时,再进行load db的操作,并回设缓存,最后删除mutex key
    4. 当操作返回失败时,证明有线程在load db,当前线程睡眠一段时间再重试整个get缓存的方法

缓存雪崩

问题描述

key对应数据存在,但在redis中过期,此时若有大量并发请求过来,这些请求发现缓存过期一般都会从后端DB加载数据并回设到缓存,这个时候大并发的请求可能会瞬间把后端DB压垮。

缓存雪崩与缓存击穿的区别在于缓存雪崩针对很多key缓存,前者则是某一个key

解决方案

  1. 构建多级缓存架构:nginx缓存+redis缓存+其它缓存(ehcache等)
  2. 使用锁或队列:用加锁或队列的方式保证不会有大量的线程对数据库一次性进行读写,从而避免失效时大量的并发请求落到底层存储系统上,不适用于高并发情况
  3. 设置过期标志更新缓存:记录缓存数据是否过期(设置提前量),如果过期会触发通知另外的线程在后台去更新实际key的缓存
  4. 将缓存失效时间分散开:比如可以在原有的失效时间基础上增加一个随机值,如1~5分钟随机,这样每个缓存的过期时间的重复率应付降低,就很难引发集体失效的事件

分布式锁

问题描述

随着业务发展的需要,原单体单机部署的系统被演化成分布式集群系统后,由于分布式系统多线程、多进程并且分布在不同机器 上,使得原单机部署情况下的并发控制锁策略失效,单纯的Java API并不能提供分布式锁的能力,为了解决这个问题就需要一种跨JVM的互斥机制来控制共享资源的访问,这就是分布式锁要解决的问题

分布式锁主流的实现方案:

  1. 基于数据库实现分布式锁
  2. 基于缓存(Redis等)
  3. 基于Zookeeper

每种分布式锁解决方案都有各自的优缺点:

  • 性能:Redis最高
  • 可靠性:zookeeper最高

解决方案:使用Redis实现分布式锁

  • setnx lock 1:上锁
  • del lock:释放锁

  1. 多个客户端同时获取锁(setnx)
  2. 获取成功,执行业务逻辑(从db获取数据,放入缓存),执行完成释放锁(del)
  3. 其它客户端等待重试

问题:setnx刚好获取到锁,业务逻辑出现异常,导致锁无法释放

解决:设置过期时间,自动释放锁

优化-设置锁的过期时间

  • 通过expire设置过期时间(缺乏原子性,如果在setnxexpire之间出现异常,锁也无法释放)

  • set时指定过期时间(推荐)

  • set lock 1 NX EX 12:设置锁的同时设置过期时间为12秒

    • EX:表示过期时间的单位是秒
    • PX:表示过期时间的单位是毫秒

问题:可能会释放其它服务器的锁

解决:setnx获取锁时,设置一个指定的唯一值(如:UUID),释放前获取这个值,判断是否是自己的锁

优化-UUID防误删

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
@RestController
@RequestMapping("/redisTest")
public class RedisTestController {
@Autowired
private RedisTemplate redisTemplate;

@GetMapping("testLock")
public void testLock(){
// 1. 获取锁,3秒后过期,使用UUID防止误删,uuid表示不同的操作
String uuid = UUID.randomUUID().toString();
Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock", uuid, 3, TimeUnit.SECONDS);
// 2. 判断锁
if(lock){
Object value = redisTemplate.opsForValue().get("num");
if(StringUtils.isEmpty(value)){
return;
}
int num = Integer.parseInt(value+"");
// 更新值
redisTemplate.opsForValue().set("num", ++num);
// 释放锁时,判断当前uuid和释放锁uuid是否一样,如果一样才释放
if(uuid.equals(redisTemplate.opsForValue().get("lock"))){
redisTemplate.delete("lock");
}
}else{
// 获取锁失败
try {
Thread.sleep(100);
testLock();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

问题:删除操作缺乏原子性

解决:使用LUA脚本保证删除的原子性

优化-LUA脚本保证删除的原子性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
@RestController
@RequestMapping("/redisTest")
public class RedisTestController {
@Autowired
private RedisTemplate redisTemplate;

@GetMapping("testLock")
public void testLock(){
// 1. 获取锁,3秒后过期,使用UUID防止误删,uuid表示不同的操作
String uuid = UUID.randomUUID().toString();
Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock", uuid, 3, TimeUnit.SECONDS);
// 2. 判断锁
if(lock){
Object value = redisTemplate.opsForValue().get("num");
if(StringUtils.isEmpty(value)){
return;
}
int num = Integer.parseInt(value+"");
// 更新值
redisTemplate.opsForValue().set("num", ++num);
// 释放锁时,判断当前uuid和释放锁uuid是否一样,如果一样才释放
if(uuid.equals(redisTemplate.opsForValue().get("lock"))){
String script = "if redis.call('get', KEYS[1])==ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
redisScript.setScriptText(script);
redisScript.setResultType(Long.class);
redisTemplate.execute(redisScript, Arrays.asList("lock"), uuid);
}
}else{
// 获取锁失败
try {
Thread.sleep(100);
testLock();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

总结

  1. 加锁
  2. 使用lua释放锁
  3. 重试

为确保分布式锁可用,至少要确保锁的实现同时满足以下四个条件:

  • 互斥性。在任意时刻,只有一个客户端能持有锁
  • 不会发生死锁。即使有一个客户端在持有锁的期间崩溃而没有主动解锁,也能保证后续其它客户端能加锁
  • 解铃还须系铃人。加锁和解锁必须是同一个客户端,客户端自己不能把别人加的锁给解了
  • 加锁和解锁必须具有原子性

Redis6新特性

Redis6新数据类型

Bitmaps

介绍

  • Redis提供了Bitmaps这个“数据类型”可以实现对位的操作,
    • Bitmaps本身不是一种数据类型,实际上它就是字符串(key-value),但是它可以对字符串的位进行操作
      • Bitmaps单独提供了一套命令,所以在Redis中使用Bitmaps和使用字符串的方法不太相同。可以把Bitmaps想象成一个以位为单位的数组,数组的每个单元只能存储0和1,数组的下标在Bitmaps中叫做偏移量

相关命令

  • setbit <key> <offset> <value>:设置Bitmaps中某个偏移量的值(0或1)
    • offset:偏移量从0开始
    • 如果第一次初始化时指定的偏移量很大,会造成redis的性能下降
  • getbit <key> <offset>:获取Bitmaps中某个偏移量的值
  • bitcount:统计字符串被设置为1的bit数。一般情况下,给定的整个字符串都会被进行计数,通过指定额外的start或end参数,可以让计数只在特定的位上进行,start和end参数的设置,都可以使用负数值:如-1表示最后一位,而-2表示倒数第二位,start和end是指bit组的字节的下标数,二者皆包含。
    • bitcount <key> [start end]:统计字符串从start字节到end字节比特值为1的数量,即每次统计的是至少8位
  • bitop and(or/not/xor) <destkey> [key...]:bitop是一个复合操作,可以做多个Bitmaps的and(与)、or(或)、not(非)、xor(异或)操作并将结果保存在destkey中

HyperLogLog

介绍

  • 在开发中,经常会遇到与统计相关的功能需求,如统计网站PV(PageVIew页面访问量),可以使用Redis的incr、incrby轻松实现

  • 但像UV(UniqueVisitor,独立访客)、独立IP数、搜索记录数等需要去重和计数的问题如何解决?这种求集合中不重复元素个数的问题称为基数问题。

  • 解决基数问题有很多方案:

    1. 数据存储在MySQL表中,使用distinct、count计算不重复个数
    2. 使用Redis提供的hash、set、bitmaps等数据结构来处理

    这些方案结果精确,但随着数据不断增加,导致占用空间越来越大,对于非常大的数据集是不切实际的

  • Redis推出了HyperLogLog,HyperLogLog是用来做基数统计的算法,HyperLogLog的优点是在输入元素或者体积非常非常大时,计算基数所需的空间总是固定的,并且是很小的。

  • 在Redis里面,每个HyperLogLog键只需要花费12KB内存,就可以直接计算接近\(2^{64}\)个不同元素的基数。这和计算基数时,元素越多耗费内存就越多的集合形成鲜明对比

  • 但是,因为HyperLogLog只会根据输入元素来计算基数,而不会存储输入元素本身,所以HyperLogLog不能像集合那样,返回输入的各个元素

    • 什么是基数?

      如数据集{1,3,5,7,5,7,8},则这个数据集的基数集为{1,3,5,7,8},基数(不重复元素)为5,基数估计就是在误差可接受范围内,快速计算基数

相关命令

  • pfadd <key> <element> [element ...]:添加指定元素到HyperLogLog中,如果执行命令后近似基数发生变化,则返回1,否则返回0
  • pfcount <key> [key ...]:统计近似基数值
  • pfmerge <destkey> <sourcekey> [sourcekey...]:将一个或多个HyperLogLog合并后的结果存在另一个HyperLogLog

Geospatial

介绍

  • Redis 3.2中增加了对GEO类型的支持,GEO(Geographic),地理信息的缩写。该类型就是元素的二维坐标,在地图上就是经纬度。Redis基于该类型,提供了经纬度设置,查询,范围查询,距离查询,经纬度Hash等常见操作

相关命令

  • geoadd <key> <longitude> <latitude> <member> [longitude latitude member ...]:添加地理位置(经度,纬度,名称)

    注:两极无法直接添加

    有效的经度从-180度到180度;有效的纬度从-85.05112878度到85.05112878度,当坐标超出指定范围是,该命令将会返回一个错误,已经添加的数据是无法再往里面添加的

  • geopos <key> <member> [member...]:获得指定地区的坐标值

  • geodist <key> <member1> <member2> [m|km|ft|mi]:获取两个位置之间的直线距离

    • m:单位米(默认)
    • km:单位千米
    • mi:单位英里
    • ft:单位英尺
  • georadius <key> <longitude> <latitude> radius m|km|ft|mi:以给定经纬度为中心,找出某一半径内的元素

Redis6新功能

ACL

  • Redis ACL是Access Control List(访问控制列表)的缩写,该功能允许根据可以执行的命令和可以访问的键来限制某些连接
  • 在Redis5之前,Redis安全规则只有密码控制,还有通过rename来调整高危命令比如flushdbkeys *shutdown等。Redis6则提供ACL的功能对用户进行更细粒度的权限控制:
    1. 接入权限:用户名和密码
    2. 可以执行的命令
    3. 可以操作的key

相关命令

  • acl list:查看用户权限列表
    • user default on nopass ~* &* +@alluser default:用户;on:启用该用户;nopass:没有密码;~* &*:能操作哪些key;+@all:能操作哪些命令
  • acl cat:查看权限指令类别
    • 加参数类型名可以查看类型下具体命令,如:acl cat string
  • acl whoami:查看当前用户
  • aclsetuser:创建和编辑用户ACL
    • 启用/禁用:on/off
    • 权限添加删除:
      • +<command>-<command>:向用户可执行指令列表中添加或移除命令
      • `+@<category>-@<category>:从用户可调用指令中添加或移除类别
      • allcommandsnocommand+@all-@all的别名
    • 可操作键的添加或删除:
      • ~<pattern>:添加可作为用户可操作的键的模式,如~*允许所有的键
  • 例:
    • 通过命令创建新用户默认权限:acl setuser tom
    • 设置用户名、密码、ACL权限、并启用的用户:acl setuser tom on >mypassword ~cached:* +get
    • 登录用户:auth tom mypassword

IO多线程

  • IO多线程其实指客户端交互部分的网络IO交互处理模块多线程,而非执行命令多线程。

  • 执行命令仍然是单线程

  • 多线程IO默认是不开启的,需要在配置文件中配置

    1
    2
    io-threads-do-reads yes
    io-threads 4

工具支持Cluster

  • 官方redis-benchmark工具开始支持cluster模式,通过多线程的方式对多个分片进行压测

其它

  1. RESP3新的通信协议:优化服务端与客户端之间的通信

  2. Client site caching客户端缓存:基于RESP3协议实现的客户端缓存功能。为了进一步提升缓存的性能,将客户端经常访问的数据cache到客户端。减少TCP网络交互

  3. Proxy集群代理模式:Proxy功能,让Cluster拥有像单实例一样的接入方式,降低大家使用cluster的门槛。不过需要注意的是代理不改变Cluster的功能限制,不支持的命令还是不会支持,如跨slot的多key操作

  4. Modules API

    Redis6中模块API开发进展非常大。