Redis 简介
Redis 是一个C语言开发的,基于键值对的内存存储系统,支持RDB和AOF持久化,可以用作数据库、缓存和消息中间件。 它支持多种类型的数据结构,如 字符串(String), 散列(Hash), 列表(List), 集合(Set), 有序集合(Sorted Set)。
Redis 常用数据结构
常用Redis命令
KEYS * 获取所有的键名列表(KEYS pattern (pattern可以是?:一个字符,*:任意个字符,[a-f]:a-f之间任意一个字符),\x:匹配字符x)
EXISTS key:判断key是否存在,存在返回1,不存在返回0
DEL key([k1,k2]):删除key,支持多个key,返回删除的个数
TYPE key([k1,k2]):获取key所对应值得类型,支持多个key(string,hash,list,set,zset)
字符串
存储的数据格式类似Map<String,String>,可以储存任意形式的字符串类型,二进制数据,Json化对象,字节数组等,一个字符串类型存储的最大数据容量为512MB,Redis的key的最大容量也是512MB。
常用方法:
SET key value [NX|XX] [EX seconds] [PX milliseconds]
set(key, value, nxxx, expx, time)
EX:设置过期时间(单位秒)
PX:设置过期时间(单位毫秒)
NX:只有key不存在的时候设置value
XX:只有key存在的时候设置value
SETEX key seconds value :设置值的同时设置key的过期时间(秒)相当于SET mykey value +EXPIRE mykey seconds
PSETEX key milliseconds valu:PSETEX和SETEX一样,唯一的区别是到期时间以毫秒为单位,而不是秒
SETNX key value :当key不存在的时候设置值,存在的时候不操作
SET key value
GET key
INCR key :将key中存储的数值+1,返回的是递增后的值。如果该key不存在,则初始化key为0。如果类型不对或者不是整数,则报错
INCRBY key i: 将key中存储的数值+i
DECR key: 将key中存储的数值-1
DECRBY key i: 将key中存储的数值-i
APPEND key value:将key中存储的值追加上value
STRLEN key:获取key中存储的值得长度
MSET k1,v1,k2,v2
MGET k1,k2
GETSET key newValue :将key对应的value值设置成newValue,并返回老的value
散列
可以存储的数据格式类似为:Map<String,Map<String,String>>,适合存储对象。
常用方法:
HSET key field value (不区分插入或更新操作,插入返回1,更新返回0)
HGET key field
HMSET key f1 v1 f2 v2…
HMGET key f1 f2..
HGETALL key 获取所有的
HEXISTS key field 判断value是否存在
HSETNX key field value: 插入数据(数据不存在,同HSET),不做任何操作(当数据存在时)
HINCRBY key field i:将key filed 对应的value值增加i
HDEL key f1 f2.. :删除,返回删除的个数
HKEYS key :获取字段名(即key 对应所有的field)
HVALS key :获取字段值(即key 对应所有的value)
HLEN key :获取字段的数量(即key 对应所有的field的数量)
列表
存储的数据格式类似:Map<String, List<String>>
常用方法
LPUSH keyv1 v2 .. :将1个或多个值从左边依次插入,先插入v1在后边,再插入v2在左边 (右:RPUSHkey v1 v2 )
LPOP key :从左边移除列表第一个元素并返回 (右边移除: RPOP key)
LPUSHX keyv1 v2:将1个或多个值从左边插入到已经存在的列表中
LINDEX key index :通过索引获取列表中元素(最后插入的索引为0,依次往前推,负数表示从后往前,-1表示最后一个,-2表示倒数第二个,没有RINDEX)
LRANGE keyiStart iStop :通过索引范围(闭区间[ ])获取列表中元素(没有RRANGE)
LSET keyindex value :通过索引设置列表的元素的值
LTRIM keyiStart iStop :保留索引范围内(闭区间)的元素,其他元素删除
LREM keycount value :从列表中删除字段值为value的元素,删除个数是count的绝对值(count>0从左边删除,count=0全部删除,count<0从右边删除)
RPOPLPUSH resource destination:原子性的返回并移除resource 列表中最后一个元素(尾部)并把它添加到destination列表的第一个位置(列表头部)
例如:假设 source 存储着列表a,b,c, destination存储着列表 x,y,z。执行 RPOPLPUSH 得到的结果是 source 保存着列表 a,b ,而 destination 保存着列表 c,x,y,z。
如果 source 不存在,那么会返回 nil 值,并且不会执行任何操作。 如果 source 和 destination 是同样的,那么这个操作等同于 移除列表最后一个元素并且把该元素放在列表头部, 所以这个命令也可以当作是一个旋转列表的命令。
BLPOP key1key2.. timeout : 移除并获取列表的第一个元素,如果列表没有元素,则会一直阻塞列表知道等待超时或者发现可弹出元素(timeout=0则会一直等待),先从key1对应的列表取,取到就返回key1和对应的元素,没有去取key2,同前一个。
BRPOP key1key2.. timeout : 移除并获取列表的最后一个元素,如果列表没有元素,则会一直阻塞列表知道等待超时或者发现可弹出元素
LINSERT keyBEFORE/AFTER target value : 在key对应的列表中找target元素,找到后在他之前或之后插入value元素
LLEN key :返回列表长度
集合
存储的数据格式类似Map<String,set<String>>,Redis集合数据类型是String类型的无序集合,集合成员是唯一的,不能出现重复的数据(插入重复元素,Redis会忽略操作)
常用方法:
SADD key m1 m2.. :向key对应的集合中添加多个元素
SREM key m1 m2.. : 移除key对应集合中的多个元素
SPOP key :随机移除集合中的一个元素
SMEMBERS key :返回集合中的所有元素
SCARD key :返回集合中元素的个数
SISMEMBER key member : 判断member是否是集合元素
SMOVE resource destination member : 将resource集合的member元素移到destionation中
SDIFF key1 [key2..] : 以key1为基准,返回key1有且[key2 key3..等]没有的元素
SINTER key1 [key2…] :返回所有集合的交集!
SINTERSTORE destination key1 [key2..] :获取所有集合的交集并存储在destionation集合中
SUNION key1 [key2…] :返回所有集合的并集
SUNIONSTORE destination key1 [key2..] : 获取所有集合的交集并存储在destionation集合中
有序集合
存储的数据格式Map<String,zSet<String>>,不允许重复的值,每个元素都关联一个double类型的分数,分数可以重复,redis有序集合按照分数从小到大排序。 Redis有序集合默认是升序的,分数越小排名越靠前,即分数越低元素下标越小
常用方法:
ZADD key score1 member1 [score2 member2 ...] 添加一个或多个成员到有序集合,或者如果它已经存在更新其分数
ZRANGE key start stop [WITHSCORES] 把集合排序后,返回名次在[start,stop]之间的元素。 WITHSCORES是把score也打印出来
ZREVRANGE key start stop [WITHSCORES] 倒序排列(分数越大排名越靠前),返回名次在[start,stop]之间的元素
ZRANGEBYSCORE key min max [WITHSCORES] [LIMIT offset n] 集合(升序)排序后取score在[min, max]内的元素,并跳过offset个,取出n个
ZREM key member [member ...] 从有序集合中删除一个或多个成员
ZRANK key member 确定member在集合中的升序名次
ZREVRANK key member 确定member在集合中的降序名次
ZSCORE key member 获取member的分数
ZCARD key 获取有序集合中成员的数量
ZCOUNT key min max 计算分数在min与max之间的元素总数
ZINCRBY key increment member 给member的分数增加increment
ZREMRANGEBYRANK key start stop 移除名次在start与stop之间的元素
ZREMRANGEBYSCORE key min max 移除分数在min与max之间的元素
Redis中的数据库
Redis服务器将所有数据库都保存在服务器状态redis.h/redisServer结构的db数组中,db数组都是一个redis.h/redisDb结构,每个redisDb结构代表一个数据库,在初始化服务器时,会根据服务器的状态的dbnum属性来决定创建多少个数据库。由服务器配置的database选项决定,默认是16个
struct redisServer {
// ...
// 一个数组,保存着服务器中所有数据库
redisDb * db;
//服务器中db数量
int dbnum
//...
};
默认情况下Redis客户端使用0号数据库组作为目标数据库,可以通过SELECT命令来切换,在服务器内部,客户端状态redisClient结构的db属性记录目标数据库,指向redisDb结构的一个指针,如下图
typedef struct redisClient {
// ...
// 记录客户端当前正在使用的db
redisDb *db
//...
} redisClient
Redis服务器中所有数据库都是用redisDb结构表示,其中redisDb结构的dict字典保存了数据库中所有键值对,这个字典我们称为键空间(key space)
typedef struct redisDb {
// ...
// 数据库键空间,保存所有键值对
dict *dict
// 过期字典,保存着键的过期时间
dict *expires
//...
} redisDb
Redis持久化
因为Redis是内存数据库,所有数据都存储在内存中,在宕机或者重启时数据就会丢失,为此,Redis提供了两种持久化方式,可以将Redis内存中的数据库状态保存到磁盘中,避免意外丢失。
RDB持久化
RDB持久化可以手动执行也可以根据服务器配置选项定期执行,将某个时间点上的数据库状态保存到一个RDB文件中(磁盘中),RDB文件是一个经过压缩的二进制文件,可以通过该文件还原到生成RDB文件时的数据库状态。
RDB文件的创建
手动保存
通过以下两个Redis命令手动生成RDB文件
- SAVE命令:SAVE命令会阻塞Redis服务器进程,直到RDB文件创建完毕,在服务器阻塞期间,不能处理任何命令请求
- BGSAVE命令:BGSAVE不会阻塞Redis服务器进程,它会fork一个子进程,然后由子进程负责创建RDB文件,服务器进程(父进程)继续处理命令请求
以上两个命令实际底层是调用rdb.c/rdbSave函数完成,只是调用的方式不同。注意BGSAVE命令和SAVE命令不能同时执行,后执行命令会被拒绝;BGREWAITEAOF命令和BGSAVE命令也不能同时执行,因为这两个命令实际工作都是由子进程完成。
注:Redis BGREWAITEAOF命令用于手动异步执行一个 AOF(AppendOnly File) 文件重写操作。重写会创建一个当前 AOF 文件的体积优化版本。
自动保存
Redis通过配置redis.cfg文件的save选项,让服务器每隔一段时间自动执行一次BGSAVE命令(不阻塞),save选项设置多个保存条件,其中任意一个条件满足,就会执行BGSAVE命令,默认的保存条件如下:
- save 900 1:900秒内,对数据库进行至少1次修改
- save 300 10:300秒内,对数据库进行至少10次修改
- save 60 10000:60秒内,对数据库进行至少10000次修改
服务器程序会根据save选项设置的保存条件,设置服务器状态redisServer结构的saveparams属性,saveparams属性是一个数组,每个元素都是saveParam结构,保存一个save选项:
struct redisServer {
// ...
// 一个数组,保存着服务器中所有数据库
redisDb * db;
//服务器中db数量
int dbnum;
//记录了保存条件的数组
struct saveparam *saveparams;
//...
};
struct saveparam {
// 秒数
time_t seconds;
//修改数
int changes;
};
RDB文件的载入
RDB文件的载入是服务器启动时候自动执行的,只要Redis服务器在启动时检测到RDB文件的存在,就会自动载入RDB文件,没有特定命令。底层的工作由rdb.c/rdbLoad函数完成,载入RDB文件期间一直处于阻塞状态,直至完成。
dirty计数器和lastsave属性
除了saveParams数组之外,服务器状态还维护了一个dirty计数器和lastsave属性
- dirty计数器记录距离上一次成功执行SAVE命令或者BGSAVE命令之后,服务器对数据库状态(所有数据库)进行了多少次修改(包括写入、删除、更新等)
- lastsave属性是一个UNIX时间戳,记录了服务器上一次成功执行SAVE命令或者BGSAVE命令的时间。
struct redisServer {
// ...
// 一个数组,保存着服务器中所有数据库
redisDb * db;
//服务器中db数量
int dbnum;
//记录了保存条件的数组
struct saveparam *saveparams;
//修改计数器
long long dirty;
//上一次执行保存的时间
time_t lastsave;
//...
};
周期性操作函数
Redis服务器的周期性操作函数serverCron默认每隔100毫秒执行一次,用于对正在运行的服务器进行维护,包括:检查save选项所设置的保存条件(遍历saveparams数组中所有保存条件)是否满足,如果满足执行BGSAVE命令。
RDB文件结构
主要包括:
REDIS:5个字符,常量的字符,载入文件快速检查载入的文件是否是RDB文件
db_version:4个字节,是一个字符串表示的整数,记录RDB文件的版本号,如0006表示RDB文件的版本为第六版
databases:表示零个或任意多个数据库,以及各个数据库中键值对数据,如果服务器的所有数据库都是空,则这个部分也为空,占0字节;如果数据库不为空,这个部分按照实际数据库及其保存的键值对,长度也有所不同
EOF:常量,长度为1个字节,标记RDB文件正文内容结束
check_num:是一个8字节长的无符号整数,保存一个校验和,由前四部分内容计算得到,载入数据所计算出的校验与该值对比,检查RDB文件是否出错或者损坏。
databases部分
一个RDB文件的databases部分可以保存任意多个非空数据库,如下:
每个database在RDB文件中保存为SELECTDB、db_number、key_value_pairs三个部分
- SELECTDB:1个字节,表示下一个是数据库号码
- db_number:数据库号码,可以是1字节、2字节、5字节,读db_number部分后,服务器调用SELECT命令切换数据库
- key_value_pairs:保存所有键值对
key_value_pairs部分
保存一个或以上数量的键值对,如果带有过期时间,键值的过期时间也会被保存,如下:
TYPE常量代表一种对象类型或者底层编码,程序会根据TYPE值来决定如何读入和解释value数据,主要包括
- REDIS_RDB_TYPE_STRING
- REDIS_RDB_TYPE_LIST
- REDIS_RDB_TYPE_SET
- REDIS_RDB_TYPE_ZSET
- REDIS_RDB_TYPE_HASH
- REDIS_RDB_TYPE_LIST_ZIPLIST
- REDIS_RDB_TYPE_SET_INTSET
- REDIS_RDB_TYPE_ZSET_ZIPLIST
- REDIS_RDB_TYPE_HASH_ZIPLIST
EXPIRETIME_MS常量1个字节,表示下一个写入的是一个以毫秒为单位的过期时间
ms是一个8字节长的带符号的整数,记录一个以毫秒为单位的UNIX时间戳,这个时间戳就是键值对的过期时间。
AOF持久化
AOF(Append Only File)持久化通过保存Redis服务器所执行的写命令来记录数据库状态的,可以分为:命令追加、文件写入、文件同步三个步骤
命令追加
当AOF持久化功能开启时,服务器在执行完一个写命令后,会以协议格式将被执行的写命令追到到服务器状态的aof_buf缓冲区的末尾
struct redisServer {
// ...
// 一个数组,保存着服务器中所有数据库
redisDb * db;
//服务器中db数量
int dbnum;
//记录了保存条件的数组
struct saveparam *saveparams;
//修改计数器
long long dirty;
//上一次执行保存的时间
time_t lastsave;
//AOF缓冲区
sds aof_buf
//...
};
开启AOF,执行以下命令:
SET msg "hello"
SADD fruits "apple" "banana" "cherry"
RPUSH numbers 128 256 512
查看AOF文件如下:
*2\r\n$6\r\nSELECT\r\n$1\r\n0\r\n
*3\r\n$3\r\nSET\r\n$3\r\nmsg\r\n$5\r\nhe11o\r\n
*5\r\n$4\r\nSADD\r\n$6\r\nfruits\r\n$5\r\napple\r\n$6\r\nbanana\r\n$6\r\ncherry\r\n
*5\r\n$5\r\nRPUSH\r\n$7\r\nnumbers\r\n$3\r\n128\r\n$3256\r\n$3\r\n512\r\n
文件写入和同步
Redis的服务器进程就是一个事件循环(loop),在循环中文件事件负责接收客户端的命令请求,以及向客户端发送命令回复,而时间事件负责执行像serverCron函数这样需要定时运行的函数。
处理文件事件可能会执行一些写命令,内容追加到aof_buf缓冲区中,服务器在每次结束一个事件循环之前,调用flushAppendOnlyFile函数,考虑是否将缓冲数据刷到AOF文件中。伪代码如下:
def eventloop():
while True:
#处理文件事件,接受命令请求,发送命令回复
#处理命令请求时候(写命令时)可能会有新的内容被追加到aof_buf缓冲区中
processFileEvents()
#处理时间事件
processTimeEvents()
#考虑是否要将aof_buf中内容写入到AOF文件中
flushAppendOnlyFile()
flushAppendOnlyFile函数行为根据服务器配置redis.conf文件的appendfsync选项的值来决定
- always :将aof_buf缓冲区中的所有内容写入并同步到AOF文件
- everysec:将aof_buf缓冲区中的所有内容写入到AOF文件,同步AOF时间超过1s则再次同步,同步操作由一个线程专门负责执行
- no:将aof_buf缓冲区中的所有内容写入到AOF文件,但不对AOF文件进行同步,何时同步由操作系统决定
默认值为everysec,当appendfsync的值为always时,服务器在每个事件循环都要将aof_buf缓冲区的所有内容写入并同步到AOF文件,效率最慢,安全性(数据丢失)最高,即是出现停机,仅丢失一个事件循环中产生的命令。everysec会丢失1秒内的命令数据,no将丢失全部数据,不会同步AOF文件。
fsync和fdatasync同步函数
当用户调用write函数,将一些数据写入到文件的时候,操作系统通常会将写入数据暂时保存在内存缓冲区里面,等到内存缓冲区被写满或者超过指定的限制时,才真正的将缓冲区的数据写入到磁盘里面,这种做法虽然提交效率,但是在发生停机情况下,内存缓冲的数据将丢失,为此系统提供了fsync和fdatasync两个同步函数,可以强制让操作系统将缓冲区数据立即写入到磁盘里面,确保安全性。
AOF文件载入
AOF文件包含重建数据库状态的所有写命令,所以读取并重新执行一遍AOF文件里面保存的写命令即可,步骤如下:
- 服务器启动载入程序,创建一个不带网络连接的伪客户端(fake client)(载入AOF文件不需要网联连接)
- 从AOF文件中分析并读取一条写命令,使用伪客户端执行被读出的写命令
- 重复2直到所有的AOF文件中的所有写命令都被处理完毕
AOF重写
随着不断运行,AOF文件越来越大,为了解决这个问题,Redis提供了AOF重写(rewrite)功能:Redis服务器可以创建一个新的AOF文件替代现有的AOF文件,新旧两个AOF文件保存的数据库状态相同,但是新AOF文件不会包含浪费空间的冗余命令,所以比旧的AOF文件要小。
AOF重写的实现
AOF重写不需要读取、分析和操作旧AOF文件,而是通过读取服务器当前数据库状态完成:新的AOF通过读取现有的值然后使用一个新的命令替代之前可能的多个命令
在实际过程中,为了避免执行命令造成客户端输入缓冲区溢出,重写程序在处理列表、哈希、集合、有序集合这四种可能带有多个元素的键时,如果元素数量超过redis.h/REDIS_AOF_REWRITE_TIEMS_PER_CMD常量的值,就会使用多条命令,而不是一个命令包含过长的值,默认值为64。
AOF重写缓冲区
因为AOF重写程序是在Redis子进程中进行,所以AOF的重写不影响先用的Redis的使用,但是可能会造成服务器当前数据库状态和重写的AOF文件所保存的数据库状态不一致。为此,Redis服务器设置了一个AOF重写缓冲区,在服务器创建子进程后Redis服务器执行完一个写命令后,会同时发送个AOF缓冲区和AOF重写缓冲区
即子进程在执行AOF重写期间,服务器进程需要执行以下工作
- 执行客户端发来的命令
- 将执行后的写命令追加到AOF缓冲区和AOF重写缓冲区
而当子进程完成AOF重写后,向父进程发送一个信号,父进程在接受信号后调用信号处理函数,执行以下工作:
- 将AOF重写缓冲区的文件的所有内容写入到新的AOF文件中,新的AOF文件所保存的数据库状态和服务器当前状态一致
- 对新的AOF文件进行改名,原子地覆盖现有AOF文件,完成替换。
注意:整个AOF后台重写过程只有在信号处理函数执行过程中,父进程会阻塞。
RDB和AOF的区别和联系
AOF文件的更新频率通常比RDB文件的更新频率高,所以如果数据库开启了AOF持久化功能,那么服务器就会优先使用AOF文件还原数据库状态,只有在AOF持久化功能处于关闭状态时,服务器才会使用RDB文件还原数据库状态
Redis键的操作
当使用Redis命令时添加、删除、更新、读取操作外,服务器不仅会对键空间执行指定的读写操作,还会执行额外的维护操作,如下:
- 读取键后(读和写操作都需读键),服务器会根据键是否存在来更新服务器中键空间的命中次数hit和不命中次数miss,通过INFO stats命令的keyspace_hits属性和keyspace_misses属性查看
- 读取一个键后,服务器会更新键的LRU时间,这个值可以用于计算键的闲置时间,OBJECT idletime key查看
- 如果读取一个键并发现已经过期,服务器会删除这个键
- 如果客户端使用WATCH命令监视某个键,当服务器在对被监视的键进行修改,会将这个键标记为脏ditrty
- 服务器每修改一个键后,都会对脏键计数器+1,这个计数器会触发服务器持久化和复制操作
- 如果开启服务器通知,则对键修改后服务器按照配置发送相应的数据库通知
KEY过期时间
Redis有四个不同的命令用于设置键的生存时间,如下:
- EXPIRE key ttl :将键key的生存时间设置为ttl秒
- PEXPIRE key ttl:将键key的生存时间设置为ttl毫秒
- EXPIREAT key timestamp:将键key的过期时间设置为timestamp所指定的秒数时间戳
- PEXPIREAT key timestamp:将键key的过期时间设置为timestamp所指定的毫秒数时间戳
最终EXPIRE、PEXPIRE、EXPIREAT三个命令都会转换成PEXPIREAT命令,在redisDb结构的expires字典保存了数据库中所有键的过期时间,过期字典的键是一个指针,指针只想键空间中某个键对象,字典的值是一个long long类型的整数,保存了过期时间,一个毫秒精度的UNIX时间戳。
移除过期时间
通过PERSIST命令移除一个键的过期时间,通过TTL命令可以计算并返回剩余生存时间
Redis过期键的删除策略
三种删除策略
- 定时删除:在设置键过期时间的同时,创建一个定时器timer,让定时器在键过期时间来临时,立即执行对键的删除操作
- 惰性删除:每次从键空间获取键的时候,检查该键是否过期,如果过期则删除,否则返回
- 定期删除:每隔一段时间,程序就对数据库进行一次检查, 删除里面的过期键,至于删除多少,检查多少个数据库由算法决定
定时删除
优点:对内存友好,保证过期键尽快删除,释放占用的内存
缺点:对 CPU不友好,在过期键比较多的情况下删除过期键这一行为占用一部分CPU,当有大量请求等待服务器处理,并且当前服务器不缺内存情况下,应该有限处理命令而非删除过期键。
惰性删除
优点:对CPU友好,只有取键的时候才会过期检查删除键不会处理其他键
缺点:对内存不友好,如果一个键已经过期但是这个键在不会使用的时候永远占据内存,相当于内存泄漏
定期删除
单纯的看定时删除和惰性删除,单一使用的时候都有明显的不足,定时删除占用CPU,影响服务器的响应时间和吞吐量,惰性删除浪费内存,有内存泄漏风险
定期删除是前两种的一种整合和折中
定期删除策略每隔一段时间执行一次删除过期键操作,并通过限制删除操作的执行时长和频率来减少删除操作对CPU的影响,有效减少过期键过多带来的内存浪费。但是定期删除比较难以确定删除操作的执行时长和频率,需要根据服务器和实际使用情况自定义配置。
如果删除操作执行过于频繁,或者执行时间太长,定期删除策略就会退化成定时删除策略,将CPU过去的消耗在删除过期键上;如果删除操作执行太少或者太短,定期删除又会和惰性删除策略一样,出现浪费内存
Redis服务器实际才占用了惰性删除+定期删除。通过配置使用这两种删除策略,服务器可以很好的合理使用CPU时间和避免浪费内存空间取得平衡
Redis惰性删除策略的实现
过期键的惰性删除策略由db.c/expireIfNeeded函数实现,所有读写数据库Redis命令在执行前都会调用expireIfNeed函数对输入键进行检查
- 如果输入键已经过期,那么expireIfNeeded函数将输入键从数据库中删除
- 如果删除键未过期,则expireIeNeeded函数不做任何处理
expireIeNeeded函数像一个过滤器,在命令执行之前过滤过期的输入键,避免执行命令
Redis定期删除策略的实现
过期间的定期删除策略有redis.c/activeExpireCycle函数实现,每当Redis的服务器周期的操作redis.c/serverCrom函数执行时,activeExpireCycle函数就会被调用,它在规定时间内,分多次遍历服务器中各个数据库,从数据库的expires字典中随机检查一部分键的过期时间,并删除其中已经过期的键
按照配置默认检查数据库的数量是16个,每个数据库检查的键数量是20,通过全局变量current_db记录当前activeExpireCycle函数检查的进度。
Redis持久化和复制功能对过期键的处理
RDB对过期键的处理
在执行SAVE命令或者BGSAVE命令时创建一个新的RDB文件时,程序会对数据库中的键进行检查,已经过期的键不会被保存到新创建的RDB文件中。即数据库中的过期键不会对生成新的RDB文件造成影响
再启动Redis服务器,如果开启RDB功能,那么服务器将对RDB文件进行载入:
如果服务器以主服务器模式运行,载入RDB文件时,程序会对文件中保存的键进行检查, 未过期的键载入到数据库,忽略过期的键,即过期键对载入RDB文件的主服务器不会造成影响
如果服务器以从服务器模式运行,载入RDB文件时,文件中保存的所有键,不论是否过期都会被载入到数据库中,因为主从服务器在数据同步时,从服务器数据库会被清空,所以过期键对载入RDB文件从服务器也不会造成影响。
AOF对过期键的处理
当服务器以AOF持久化模式运行时,如果数据库某个键已经过期,但它没有被惰性删除或者定期删除,那么AOF文件不会因为这个过期键产生任何影响,
当过期键被惰性删除或者定期删除之后,程序会向AOF文件追加(append)一条DEL命令。显示记录该键被删除
和RDB一样,在执行AOF重写时候,程序会对数据库中的键进行检查,已过期的键不会保存到重写后AOF文件,即数据库包含过期键不会对AOF重写造成影响
主从复制对过期键的处理
当服务器运行在主从复制模式下,过期键的删除动作由主服务器控制:
- 主服务器在删除一个过期键后会显式的向所有服务器发送一个DEL命令,告诉从服务器删除这个过期键
- 从服务器处理读命令读取到过期键不会判断删除,而且直接读取。从服务器只有接到主服务器的DEL命令后才会删除过去键
Redis 淘汰策略
Redis采用定期删除+惰性删除能够保证一部分过期键的删除,但是并不能完全保证删除所有的过期键,在不断使用过程中,Redis的内存会越来越高。为了不影响Redis使用,Redis提供了内存淘汰机制。添加新的key时会判断内存,如果内存不足时的缓存淘汰如下:
- noeviction:当内存不足时,新写入操作会报错(没人用)
- allkeys-lru:当内存不足时,在键空间中,移除最近最少使用的key
- allkeys-random:当内存不足时,在键空间中,随机移除某个key
- allkeys-lfu:当内存不足时,在键空间中,移除最近不经常使用的key
- volatile-lru:当内存不足时,在设置了过期时间的键空间中,移除最近最少使用的key。
- volatile-random:当内存不足时,在设置了过期时间的键空间中,随机移除某个key。
- volatile-lfu:当内存不足时,在设置了过期时间的键空间中,移除最近不经常使用的key
- volatile-ttl:当内存不足时,在设置了过期时间的键空间中,有更早过期时间的key优先移除
Redis4.0之后为maxmemory_policy淘汰策略添加了如上的两个LFU策略
LRU算法和LFU算法
- LRU:最近最少使用页面置换算法(Least Recently Used),首先淘汰最长时间未被使用的
- LFU:最近最不常用页面置换算法(Least Frequently Used),淘汰一定时期内被访问次数最少的
LRU关键是看页面最后一次被使用到发生调度的时间长短; 而LFU关键是看一定时间段内页面被使用的频率
Redis-LRU实现
在Redis中,读取一个键后,服务器会更新键的LRU时间,LRU时间记录在redisObject对象中,根据时间的长短执行LRU算法
typedef struct redisObject {
unsigned type:4;
unsigned encoding:4;
unsigned lru:LRU_BITS; /* LRU time (relative to global lru_clock) or
* LFU data (least significant 8 bits frequency
* and most significant 16 bits access time). */
int refcount;
void *ptr;
} robj;
Redis-LFU实现
在Redis-LFU算法中,为每个key维护一个计数器和最后访问时间。每次访问key的时,计数器值增加,计数器越大,代表访问越频繁,然后随着时间推移,降低计数器。在LRU算法中,24 bits的lru字段是用来记录LRU time的,在LFU中将这个字段分成16 bits与8 bits使用:
16 bits 8 bits
+----------------+--------+
+ Last decr time | LOG_C |
+----------------+--------+
- 高16 bits用来记录最近一次计数器降低的时间ldt,单位是分钟,
- 低8 bits记录计数器数值counter,最大值255
算法实现
uint8_t LFULogIncr(uint8_t counter) {
if (counter == 255) return 255;
double r = (double)rand()/RAND_MAX;
double baseval = counter - LFU_INIT_VAL;
if (baseval < 0) baseval = 0;
double p = 1.0/(baseval*server.lfu_log_factor+1);
if (r < p) counter++;
return counter;
}
- 获取一个0到1之间的随机数R
- 用1 / ( (old_value - LFU_INIT_VAL) * lfu_log_factor + 1) 计算出概率P
- 当R < P时,计数器 + 1
其中LFU_INIT_VAL为初始对象的计数器,默认是5,以便让新对象有机会累计计数器
counter并不是简单的访问一次就+1,而是采用了一个0-1之间的p因子控制增长。counter最大值为255。取一个0-1之间的随机数r与p比较,当r<p时,才增加counter,这和比特币中控制产出的策略类似。p取决于当前counter值与lfu_log_factor因子,counter值与lfu_log_factor因子越大,p越小,r<p的概率也越小,counter增长的概率也就越小。增长情况如下:
+--------+------------+------------+------------+------------+------------+
| factor | 100 hits | 1000 hits | 100K hits | 1M hits | 10M hits |
+--------+------------+------------+------------+------------+------------+
| 0 | 104 | 255 | 255 | 255 | 255 |
+--------+------------+------------+------------+------------+------------+
| 1 | 18 | 49 | 255 | 255 | 255 |
+--------+------------+------------+------------+------------+------------+
| 10 | 10 | 18 | 142 | 255 | 255 |
+--------+------------+------------+------------+------------+------------+
| 100 | 8 | 11 | 49 | 143 | 255 |
+--------+------------+------------+------------+------------+------------+
old_value越大,概率越低,lfu_log_factor是由配置文件设置,lfu_log_factor越大,概率P越小
衰减计数器每分钟会除以2(如果计数器小于等于10,则会变成递减)
- 注意:redis并不是开启了定时器进行衰减,而是在对象的lru计数器大于8位的部分用于存储计数器的更新时间,在获取对象的LFU计数器时,根据更新时间进行更新
LFU配置
#可以调整计数器counter的增长速度,lfu-log-factor越大,counter增长的越慢。
lfu-log-factor 10
#一个以分钟为单位的数值,可以调整counter的减少速度
lfu-decay-time 1
淘汰步骤:
1. 获取并判断当前内存,如果当前内存使用量大于设定的值,则开始进行内存淘汰
2. 开启循环,直到内存使用量低于设定的值,才会结束淘汰
3. 根据策略的选择,对每个db,使用过期字典或全字典进行取样(按照maxmemory_samples值),将取样的dictEntry放入pool中
- 如果有脚本正在执行或者正在加载数据,则不能进行内存释放
- 获取一个db的hashtable,生成一个0 - hashtable个数的随机整数i,如果按顺序取五次,都是NULL 则重新取随机数i
- 如果找到一个不为NULL的tableEntry,则按顺序将其的key放入pool中,
- 如果一个tableEntry中的key没达到取样数量,则顺延下一个tableEntry
- 遍历样本
- 如果淘汰策略是从过期key中淘汰(而不是主字典)则需要从过期字典中再次获取key
- 获取过期策略的idle, 如果是LRU就是访问时间,如果是LFU就是计数器,如果是TTL则是剩余过期时间
- 对要淘汰的key的idle进行升序排序
- 从第1步开始,获取其余db要释放的key
- 按照从大到小的顺序,从右侧开始,对key进行移除,如果移除成功了,就会最上层
- 判断是否超出最大内存的限制,如果还是超出,则再次新一轮取样并淘汰
Redis 发布订阅
Redis支持发布和订阅功能,主要命令如下PUBLISH、SUBSCRIBE、PSUBSCRIBE
- PUBLISH "channel_name" "message":向channel_name频道发送消息message
- SUBSCRIBE "channel_name1" "channel_name2": 订阅一个或多个频道,当有其他客户端向该频道发送消息,频道所有订阅者都会收到该消息
- PSUBSCRIBE "pattern_name1" "pattern_name2":订阅一个或多个模式
频道订阅和退订
当一个客户端执行SUBSCRIBE命令订阅某个或某些频道的时,这个客户端与被订阅频道之间就建立了订阅关系,Redis将所有的订阅关系保存在服务器状态的pubsub_channels字典里,字典的键时某个被订阅的频道,值是一个链表,记录了所有订阅这个频道的客户端。
struct redisServer{
//...
// 保存所有频道的订阅关系
dict *pubsub_channels
// 保存所有频道的订阅关系
list *pubsub_channels
//...
}
当频道新增一个订阅者时候,会在pubsub_channels字典的频道对应的链表尾段新增一个客户端,当该频道没有其他订阅者时,就会新建一个键和对应的空链表,然后再将客户端添加到链表上。
频道的退订
使用UNSUBSCRIBE命令退订某个或某些频道,服务器将其从pubsub_channels中解除关联
模式的订阅与退订
订阅模式使用PSUBSCRIBE命令,服务器将所有模式的订阅关系保存在服务器状态的pubsub_patterns属性中,pubsub_patterns是一个链表,链表的每个节点都包含一个pubsubPattern结构,其pattern属性记录了被订阅的模式,而client属性记录了订阅模式的客户端
typedef struct pubsubPattern{
//订阅模式的客户端
redisClient *client
//被订阅的模式
robj *pattern;
} pubsubPattern;
退订模式
使用PUNSUBSCRIBE命令退订某个或某些模式,在pubsub_patterns链表中找到相应的节点并删除即可。
发送消息
Redis客户端通过PUBLISH <channel> <message>命令将消息message发送给频道channel,消息会被发送给channel频道的所有订阅者,如果有模式pattern与channel相匹配,那么消息message也会发送给pattern模式的订阅者。
查看订阅信息
PUBSUB CHANNELS [pattern]
- 当不指定pattern时,可以查看当前被订阅的所有频道
- 当给定pattern时,返回当前被订阅的频道中哪些与pattern匹配的频道
PUBSUB NUMSUB
PUBSUB NUMSUB [CHANNEL-1] [CHANNEL-2] ... [CHANNEL-n]接收任意个频道返回这些频道的订阅者数量(遍历pubsub_channels字典所有键,记录符合条件的频道)
PUBSUB NUMPAT
PUBSUB NUMPAT 用于返回服务器当前被订阅模式的数量(返回pubsub_patterns链表的长度)
Redis事务
Redis使用MULTI、EXEC、WATCH等命令来实现事务功能,事务提供了一种将多个命令打包,然后一次性、按顺序的执行多个命令机制。如下:
redis> MULTI
OK
redis> SET name Practical Common Lisp
QUEUED
redis> GET name
QUEUED
redis> SET author Peter Seibel
QUEUED
redis> GET author
QUEUED
redis> EXEC
1)
OK
2) Practical Common Lisp
3) OK
4)Peter Seibel
事务开始
使用MULTI命令,标志着事务的开始,MUTLI命令可以将执行该命令的客户端切换至事务状态,即客户端状态flags属性中打开REDIS_MULTI标志
命令入队
当一个客户端处于非事务模式,发送命令后会被立即执行,处于事务模式时,客户端发送的命令为EXEC、DISCARD、WATCH、MULTI四个命令的其中之一,命令会被立即执行,其他命令(常见的操作键的命令)不会被立即执行,而是放入到事务队列中,然后向客户端返回QUEUED回复、
事务队列
Redis客户端有自己的事务状态,保存在客户端状态的mstate属性中
typedef struct redisClient{
//...
// 事务状态
multiState mstate; /*MULTI/EXEC state */
//...
} redisClient;
事务状态包含一个事务队列,事务队列以先进先出(FIFO)的方式保存人队的命令,较先入队的命令会被放到数组的前面,而较后入队的命令则会被放到数组的后面。以及一个已入队命令的计数器(也可以说是事务队列的长度):
typedef struct multistate {
//事务队列,FIFO顺序
multiCmd *commands;
//已入队命令计数
int count;
} multiState
事务队列是一个multiCmd类型的数组,数组中的每个multiCmd结构都保存了一个已入队命令的相关信息,包括指向命令实现函数的指针、命令的参数,以及参数的数量:
typedef struct multiCmd(
//参数
robj **argv;
//参数数量
int argc;
//命令指针
struct redisCommand *cmd;
)multicmd;
执行事务
当一个处于事务状态的客户端向服务器发送EXEC命令时,EXEC命令会立即被服务器执行,服务器遍历事务列表,执行列表中所有保存的命令,最后将执行命令所得的结果返回给客户端。
WATCH命令
WATCH命令相当于一个乐观锁(optimistic locking),它可以在EXEC命令执行之前监视任意数量的数据库键,在EXEC执行时检查被监视的键是否至少有一个已经被修改了,如果是,服务器会拒绝执行事务,并行客户端返回代表事务执行失败的空回复。
redis> WATCH "name"
OK
redis> MULTI
OK
redis> SET "name" "Peter"
QUEUED
redis> EXEC
(nil)
每个Redis数据库都保存着一个watched_keys字典,这个字典的键是某个被WATCH命令监视的数据库键,而字典的值所有监视相应数据库键的客户端组成的一个链表:
typedef struct redisDb
//...
// 正在被WATCH命令监视的键
dict*watched_keys;
//...
} redisDb;
通过watched_keys字典,服务器可以清楚地知道哪些数据库键正在被监视,以及哪些客户端正在监视这些数据库键。所有对数据库进行修改的命令,如SET、LPUSH、SADD、ZREM、DEL等,在执行后会调用multi.c/touchWatchKey函数对watched_keys字典进行检查,查看是否有客户端监视刚被修改键,如果有则touchWatchKey函数会将修改件的客户端的REDIS_DIRTY_CAS表示打开,表明客户端的事务安全性已经破坏。
当执行EXEC命令时,服务器会根据客户端是否打开REDIS_DIRTY_CAS标识来决定是否执行事务
Redis Lua脚本
redis.conf配置文件
#绑定的主机地址
bind 127.0.0.1
# 服务启动端口,默认为 6379 ,如果设置端口为 0 ,redis 服务将不会监听任何TCP连接
port 6379
# 设置TCP的连接队列 backlog ,默认为 511 ,backlog 队列总和 = 未完成三次握手队列 + 已完成三次握手队列
tcp-backlog 511
# 当客户端超过N秒空闲后,服务器主动断开连接,设置为 0 表示不主动断开连接
timeout 0
# 检测 TCP 连接alive状态的频率,设置为0表示不检测,建议设置为60
tcp-keepalive 300
################################# GENERAL #####################################
# 设置redis服务以后台守护进程启动,默认为 no非daemon
# 后台启动后服务的 pid 位于文件 /var/run/redis 中
daemonize no
# 设置输出日志级别,包括 debug、verbos、notice、warning
loglevel notice
# 设置日志输出文件,若为空字符串"" 或者 stdout ,则将日志从定位到 /dev/null
logfile ""
# 若要将redis日志记录到系统日志,将此参数设置为 yes
# syslog-enabled no
# 用于指定日志标识:若开启系统日志,指定日志以 redis 开头
# syslog-ident redis
# 设置系统日志输出设备,值可为 USER 或者 LOCAL0-LOCAL7,默认为local0
# syslog-facility local0
# 设置 redis 服务启动数据库的个数,默认 16 个,默认数据库为 DB 0 ,可使用 select <dbid> 进行切库,dbid为 0 至 databases-1
databases 16
# 是否总是显示redis那个"蛋糕"logo
always-show-logo yes
################################ SNAPSHOTTING ################################
# 指定在规定时间内,有多少此更新操作,就将数据同步至数据文件,可多个条件配合使用
# save <seconds> <changes>
# save ""
# 默认配置如下:15分钟内有一个更改,5分钟内有10个更改,1分钟内有10000个更改
save 900 1
save 300 10
save 60 10000
# 当RDB在后台持久化出错后,是否依然进行数据库写操作,yes:停止写操作,no:继续写操作
stop-writes-on-bgsave-error yes
# 指定存储至本地数据库时是否压缩数据,默认为yes:使用压缩,redis采用LZF压缩算法,使用会消耗CPU,不使用占内存
rdbcompression yes
# 是否校验压缩后的rdb文件,默认为yes:进行校验,开启大概有10%性能损耗
rdbchecksum yes
# 指定本地数据库文件名,默认为dump.rdb
dbfilename dump.rdb
# 指定本地数据文件存放目录
dir ./
################################# REPLICATION #################################
# 将当前服务器作为从库,同步备份主库的数据,并提供读操作
# replicaof <masterip> <masterport># replicaof 10.7.5.74 6379
# 当master服务设置了密码保护时,slave服务连接master的密码
# masterauth <master-password>
# When a replica loses its connection with the master, or when the replication
# is still in progress, the replica can act in two different ways:
#
# 1) if replica-serve-stale-data is set to 'yes' (the default) the replica will
# still reply to client requests, possibly with out of date data, or the
# data set may just be empty if this is the first synchronization.
#
# 2) if replica-serve-stale-data is set to 'no' the replica will reply with
# an error "SYNC with master in progress" to all the kind of commands
# but to INFO, replicaOF, AUTH, PING, SHUTDOWN, REPLCONF, ROLE, CONFIG,
# SUBSCRIBE, UNSUBSCRIBE, PSUBSCRIBE, PUNSUBSCRIBE, PUBLISH, PUBSUB,
# COMMAND, POST, HOST: and LATENCY.
#
replica-serve-stale-data yes
# You can configure a replica instance to accept writes or not. Writing against
# a replica instance may be useful to store some ephemeral data (because data
# written on a replica will be easily deleted after resync with the master) but
# may also cause problems if clients are writing to it because of a
# misconfiguration.
#
# Since Redis 2.6 by default replicas are read-only.
#
# Note: read only replicas are not designed to be exposed to untrusted clients
# on the internet. It's just a protection layer against misuse of the instance.
# Still a read only replica exports by default all the administrative commands
# such as CONFIG, DEBUG, and so forth. To a limited extent you can improve
# security of read only replicas using 'rename-command' to shadow all the
# administrative / dangerous commands.
replica-read-only yes
# Replication SYNC strategy: disk or socket.
#
# -------------------------------------------------------
# WARNING: DISKLESS REPLICATION IS EXPERIMENTAL CURRENTLY
# -------------------------------------------------------
#
# New replicas and reconnecting replicas that are not able to continue the replication
# process just receiving differences, need to do what is called a "full
# synchronization". An RDB file is transmitted from the master to the replicas.
# The transmission can happen in two different ways:
#
# 1) Disk-backed: The Redis master creates a new process that writes the RDB
# file on disk. Later the file is transferred by the parent
# process to the replicas incrementally.
# 2) Diskless: The Redis master creates a new process that directly writes the
# RDB file to replica sockets, without touching the disk at all.
#
# With disk-backed replication, while the RDB file is generated, more replicas
# can be queued and served with the RDB file as soon as the current child producing
# the RDB file finishes its work. With diskless replication instead once
# the transfer starts, new replicas arriving will be queued and a new transfer
# will start when the current one terminates.
#
# When diskless replication is used, the master waits a configurable amount of
# time (in seconds) before starting the transfer in the hope that multiple replicas
# will arrive and the transfer can be parallelized.
#
# With slow disks and fast (large bandwidth) networks, diskless replication
# works better.
repl-diskless-sync no
# When diskless replication is enabled, it is possible to configure the delay
# the server waits in order to spawn the child that transfers the RDB via socket
# to the replicas.
#
# This is important since once the transfer starts, it is not possible to serve
# new replicas arriving, that will be queued for the next RDB transfer, so the server
# waits a delay in order to let more replicas arrive.
#
# The delay is specified in seconds, and by default is 5 seconds. To disable
# it entirely just set it to 0 seconds and the transfer will start ASAP.
repl-diskless-sync-delay 5
# Replicas send PINGs to server in a predefined interval. It's possible to change
# this interval with the repl_ping_replica_period option. The default value is 10
# seconds.
#
# repl-ping-replica-period 10
# The following option sets the replication timeout for:
#
# 1) Bulk transfer I/O during SYNC, from the point of view of replica.
# 2) Master timeout from the point of view of replicas (data, pings).
# 3) Replica timeout from the point of view of masters (REPLCONF ACK pings).
#
# It is important to make sure that this value is greater than the value
# specified for repl-ping-replica-period otherwise a timeout will be detected
# every time there is low traffic between the master and the replica.
#
# repl-timeout 60
# Disable TCP_NODELAY on the replica socket after SYNC?
#
# If you select "yes" Redis will use a smaller number of TCP packets and
# less bandwidth to send data to replicas. But this can add a delay for
# the data to appear on the replica side, up to 40 milliseconds with
# Linux kernels using a default configuration.
#
# If you select "no" the delay for data to appear on the replica side will
# be reduced but more bandwidth will be used for replication.
#
# By default we optimize for low latency, but in very high traffic conditions
# or when the master and replicas are many hops away, turning this to "yes" may
# be a good idea.
repl-disable-tcp-nodelay no
# Set the replication backlog size. The backlog is a buffer that accumulates
# replica data when replicas are disconnected for some time, so that when a replica
# wants to reconnect again, often a full resync is not needed, but a partial
# resync is enough, just passing the portion of data the replica missed while
# disconnected.
#
# The bigger the replication backlog, the longer the time the replica can be
# disconnected and later be able to perform a partial resynchronization.
#
# The backlog is only allocated once there is at least a replica connected.
#
# repl-backlog-size 1mb
# After a master has no longer connected replicas for some time, the backlog
# will be freed. The following option configures the amount of seconds that
# need to elapse, starting from the time the last replica disconnected, for
# the backlog buffer to be freed.
#
# Note that replicas never free the backlog for timeout, since they may be
# promoted to masters later, and should be able to correctly "partially
# resynchronize" with the replicas: hence they should always accumulate backlog.
#
# A value of 0 means to never release the backlog.
#
# repl-backlog-ttl 3600
# The replica priority is an integer number published by Redis in the INFO output.
# It is used by Redis Sentinel in order to select a replica to promote into a
# master if the master is no longer working correctly.
#
# A replica with a low priority number is considered better for promotion, so
# for instance if there are three replicas with priority 10, 100, 25 Sentinel will
# pick the one with priority 10, that is the lowest.
#
# However a special priority of 0 marks the replica as not able to perform the
# role of master, so a replica with priority of 0 will never be selected by
# Redis Sentinel for promotion.
#
# By default the priority is 100.
replica-priority 100
# It is possible for a master to stop accepting writes if there are less than
# N replicas connected, having a lag less or equal than M seconds.
#
# The N replicas need to be in "online" state.
#
# The lag in seconds, that must be <= the specified value, is calculated from
# the last ping received from the replica, that is usually sent every second.
#
# This option does not GUARANTEE that N replicas will accept the write, but
# will limit the window of exposure for lost writes in case not enough replicas
# are available, to the specified number of seconds.
#
# For example to require at least 3 replicas with a lag <= 10 seconds use:
#
# min-replicas-to-write 3
# min-replicas-max-lag 10
#
# Setting one or the other to 0 disables the feature.
#
# By default min-replicas-to-write is set to 0 (feature disabled) and
# min-replicas-max-lag is set to 10.
# A Redis master is able to list the address and port of the attached
# replicas in different ways. For example the "INFO replication" section
# offers this information, which is used, among other tools, by
# Redis Sentinel in order to discover replica instances.
# Another place where this info is available is in the output of the
# "ROLE" command of a master.
#
# The listed IP and address normally reported by a replica is obtained
# in the following way:
#
# IP: The address is auto detected by checking the peer address
# of the socket used by the replica to connect with the master.
#
# Port: The port is communicated by the replica during the replication
# handshake, and is normally the port that the replica is using to
# listen for connections.
#
# However when port forwarding or Network Address Translation (NAT) is
# used, the replica may be actually reachable via different IP and port
# pairs. The following two options can be used by a replica in order to
# report to its master a specific set of IP and port, so that both INFO
# and ROLE will report those values.
#
# There is no need to use both the options if you need to override just
# the port or the IP address.
#
# replica-announce-ip 5.5.5.5
# replica-announce-port 1234
################################## SECURITY ###################################
# 登录 redis 数据库密码认证问题
# 执行命令 config get requirepass ,获取配置文件中默认认证密码,默认密码为 foobared
# requirepass foobared
# 执行命令 config set requirepass "redis" ,设置认证密码为 redis ,设置为空 "" 表示不认证
# 在执行命令前使用 auth <password> 命令进行认证
# 禁止远程修改 DB 文件地址,就是对命令进行权限控制
# 将命令重命名为空 "",表示禁用该命令
# rename-command FLASHALL ""
# 也可将命令重命名为 qazwsx741852edc ,然后将此名授权给特定用户使用即可
# rename-command CONFIG "qazwsx741852edc"
################################### CLIENTS ####################################
# 设置客户端默认最大连接数,设置为0表示不限制,默认为10000
# maxclients 10000
############################## MEMORY MANAGEMENT ################################
# 设置 redis 最大内存容量
# maxmemory <bytes>
# 内存达到上限的处理策略(lru means Least Recently Used<最近最少>,lfu means Least Frequently Used<最不常>)
# volatile-lru -> 利用LRU算法移除设置过过期时间的key
# allkeys-lru -> 利用LRU算法移除任何key
# volatile-lfu -> 利用LFU算法移除设置过过期时间的key
# allkeys-lfu -> 利用LFU算法移除任何key
# volatile-random -> 随机移除设置过过期时间的key
# allkeys-random -> 随机移除所有key
# volatile-ttl -> 移除即将过期的key
# noeviction -> 不移除key,返回报错就行
# 默认为不移除key策略
# maxmemory-policy noeviction
# 设置每次移除时的样本大小,默认5个:每次移除时选取5个样本,移除其中符合策略的key
# maxmemory-samples 5
# 从节点是否忽略maxmemory设置的值
# replica-ignore-maxmemory yes
############################# LAZY FREEING ####################################
# Redis has two primitives to delete keys. One is called DEL and is a blocking
# deletion of the object. It means that the server stops processing new commands
# in order to reclaim all the memory associated with an object in a synchronous
# way. If the key deleted is associated with a small object, the time needed
# in order to execute the DEL command is very small and comparable to most other
# O(1) or O(log_N) commands in Redis. However if the key is associated with an
# aggregated value containing millions of elements, the server can block for
# a long time (even seconds) in order to complete the operation.
#
# For the above reasons Redis also offers non blocking deletion primitives
# such as UNLINK (non blocking DEL) and the ASYNC option of FLUSHALL and
# FLUSHDB commands, in order to reclaim memory in background. Those commands
# are executed in constant time. Another thread will incrementally free the
# object in the background as fast as possible.
#
# DEL, UNLINK and ASYNC option of FLUSHALL and FLUSHDB are user-controlled.
# It's up to the design of the application to understand when it is a good
# idea to use one or the other. However the Redis server sometimes has to
# delete keys or flush the whole database as a side effect of other operations.
# Specifically Redis deletes objects independently of a user call in the
# following scenarios:
#
# 1) On eviction, because of the maxmemory and maxmemory policy configurations,
# in order to make room for new data, without going over the specified
# memory limit.
# 2) Because of expire: when a key with an associated time to live (see the
# EXPIRE command) must be deleted from memory.
# 3) Because of a side effect of a command that stores data on a key that may
# already exist. For example the RENAME command may delete the old key
# content when it is replaced with another one. Similarly SUNIONSTORE
# or SORT with STORE option may delete existing keys. The SET command
# itself removes any old content of the specified key in order to replace
# it with the specified string.
# 4) During replication, when a replica performs a full resynchronization with
# its master, the content of the whole database is removed in order to
# load the RDB file just transferred.
#
# In all the above cases the default is to delete objects in a blocking way,
# like if DEL was called. However you can configure each case specifically
# in order to instead release memory in a non-blocking way like if UNLINK
# was called, using the following configuration directives:
lazyfree-lazy-eviction no
lazyfree-lazy-expire no
lazyfree-lazy-server-del no
replica-lazy-flush no
############################## APPEND ONLY MODE ###############################
# 指定是否在每次更新操作后进行日志记录,redis默认异步将数据写入磁盘,不开启会导致断电时一段时间内的数据丢失,默认no
appendonly no
# 指定更新日志文件名,默认为appendonly.aof
appendfilename "appendonly.aof"
# 指定更新日志条件,建议使用 "everysec"
# "always":同步持久化,每次发生数据更改会立即调用fsync()方法将数据写入磁盘,数据完整性好,性能差
# "everysec":默认值,异步同步,每秒同步一次,若一秒内宕机,则存在数据丢失
# "no":永不
# appendfsync always
appendfsync everysec
# appendfsync no
# 重写时,是否可以使用appendfsync(接受客户端的写操作),默认为 no ,保证数据安全性
no-appendfsync-on-rewrite no
# redis会记录上次重写AOF文件的大小,当AOF文件增加至上次重写文件的 100% 倍,且大小大于64MB时,触发AOF重写
# auto-aof-rewrite-percentage 用于设置相对于上次AOF文件百分比,auto-aof-rewrite-min-size 用于设置另一基准值
auto-aof-rewrite-percentage 100
auto-aof-rewrite-min-size 64mb
# An AOF file may be found to be truncated at the end during the Redis
# startup process, when the AOF data gets loaded back into memory.
# This may happen when the system where Redis is running
# crashes, especially when an ext4 filesystem is mounted without the
# data=ordered option (however this can't happen when Redis itself
# crashes or aborts but the operating system still works correctly).
#
# Redis can either exit with an error when this happens, or load as much
# data as possible (the default now) and start if the AOF file is found
# to be truncated at the end. The following option controls this behavior.
#
# If aof-load-truncated is set to yes, a truncated AOF file is loaded and
# the Redis server starts emitting a log to inform the user of the event.
# Otherwise if the option is set to no, the server aborts with an error
# and refuses to start. When the option is set to no, the user requires
# to fix the AOF file using the "redis-check-aof" utility before to restart
# the server.
#
# Note that if the AOF file will be found to be corrupted in the middle
# the server will still exit with an error. This option only applies when
# Redis will try to read more data from the AOF file but not enough bytes
# will be found.
aof-load-truncated yes
# When rewriting the AOF file, Redis is able to use an RDB preamble in the
# AOF file for faster rewrites and recoveries. When this option is turned
# on the rewritten AOF file is composed of two different stanzas:
#
# [RDB file][AOF tail]
#
# When loading Redis recognizes that the AOF file starts with the "REDIS"
# string and loads the prefixed RDB file, and continues loading the AOF
# tail.
aof-use-rdb-preamble yes
################################ LUA SCRIPTING ###############################
# Max execution time of a Lua script in milliseconds.
#
# If the maximum execution time is reached Redis will log that a script is
# still in execution after the maximum allowed time and will start to
# reply to queries with an error.
#
# When a long running script exceeds the maximum execution time only the
# SCRIPT KILL and SHUTDOWN NOSAVE commands are available. The first can be
# used to stop a script that did not yet called write commands. The second
# is the only way to shut down the server in the case a write command was
# already issued by the script but the user doesn't want to wait for the natural
# termination of the script.
#
# Set it to 0 or a negative value for unlimited execution without warnings.
lua-time-limit 5000
################################ REDIS CLUSTER ###############################
#
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# WARNING EXPERIMENTAL: Redis Cluster is considered to be stable code, however
# in order to mark it as "mature" we need to wait for a non trivial percentage
# of users to deploy it in production.
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#
# Normal Redis instances can't be part of a Redis Cluster; only nodes that are
# started as cluster nodes can. In order to start a Redis instance as a
# cluster node enable the cluster support uncommenting the following:
#
# cluster-enabled yes
# Every cluster node has a cluster configuration file. This file is not
# intended to be edited by hand. It is created and updated by Redis nodes.
# Every Redis Cluster node requires a different cluster configuration file.
# Make sure that instances running in the same system do not have
# overlapping cluster configuration file names.
#
# cluster-config-file nodes-6379.conf
# Cluster node timeout is the amount of milliseconds a node must be unreachable
# for it to be considered in failure state.
# Most other internal time limits are multiple of the node timeout.
#
# cluster-node-timeout 15000
# A replica of a failing master will avoid to start a failover if its data
# looks too old.
#
# There is no simple way for a replica to actually have an exact measure of
# its "data age", so the following two checks are performed:
#
# 1) If there are multiple replicas able to failover, they exchange messages
# in order to try to give an advantage to the replica with the best
# replication offset (more data from the master processed).
# Replicas will try to get their rank by offset, and apply to the start
# of the failover a delay proportional to their rank.
#
# 2) Every single replica computes the time of the last interaction with
# its master. This can be the last ping or command received (if the master
# is still in the "connected" state), or the time that elapsed since the
# disconnection with the master (if the replication link is currently down).
# If the last interaction is too old, the replica will not try to failover
# at all.
#
# The point "2" can be tuned by user. Specifically a replica will not perform
# the failover if, since the last interaction with the master, the time
# elapsed is greater than:
#
# (node-timeout * replica-validity-factor) + repl-ping-replica-period
#
# So for example if node-timeout is 30 seconds, and the replica-validity-factor
# is 10, and assuming a default repl-ping-replica-period of 10 seconds, the
# replica will not try to failover if it was not able to talk with the master
# for longer than 310 seconds.
#
# A large replica-validity-factor may allow replicas with too old data to failover
# a master, while a too small value may prevent the cluster from being able to
# elect a replica at all.
#
# For maximum availability, it is possible to set the replica-validity-factor
# to a value of 0, which means, that replicas will always try to failover the
# master regardless of the last time they interacted with the master.
# (However they'll always try to apply a delay proportional to their
# offset rank).
#
# Zero is the only value able to guarantee that when all the partitions heal
# the cluster will always be able to continue.
#
# cluster-replica-validity-factor 10
# Cluster replicas are able to migrate to orphaned masters, that are masters
# that are left without working replicas. This improves the cluster ability
# to resist to failures as otherwise an orphaned master can't be failed over
# in case of failure if it has no working replicas.
#
# Replicas migrate to orphaned masters only if there are still at least a
# given number of other working replicas for their old master. This number
# is the "migration barrier". A migration barrier of 1 means that a replica
# will migrate only if there is at least 1 other working replica for its master
# and so forth. It usually reflects the number of replicas you want for every
# master in your cluster.
#
# Default is 1 (replicas migrate only if their masters remain with at least
# one replica). To disable migration just set it to a very large value.
# A value of 0 can be set but is useful only for debugging and dangerous
# in production.
#
# cluster-migration-barrier 1
# By default Redis Cluster nodes stop accepting queries if they detect there
# is at least an hash slot uncovered (no available node is serving it).
# This way if the cluster is partially down (for example a range of hash slots
# are no longer covered) all the cluster becomes, eventually, unavailable.
# It automatically returns available as soon as all the slots are covered again.
#
# However sometimes you want the subset of the cluster which is working,
# to continue to accept queries for the part of the key space that is still
# covered. In order to do so, just set the cluster-require-full-coverage
# option to no.
#
# cluster-require-full-coverage yes
# This option, when set to yes, prevents replicas from trying to failover its
# master during master failures. However the master can still perform a
# manual failover, if forced to do so.
#
# This is useful in different scenarios, especially in the case of multiple
# data center operations, where we want one side to never be promoted if not
# in the case of a total DC failure.
#
# cluster-replica-no-failover no
# In order to setup your cluster make sure to read the documentation
# available at http://redis.io web site.
########################## CLUSTER DOCKER/NAT support ########################
# In certain deployments, Redis Cluster nodes address discovery fails, because
# addresses are NAT-ted or because ports are forwarded (the typical case is
# Docker and other containers).
#
# In order to make Redis Cluster working in such environments, a static
# configuration where each node knows its public address is needed. The
# following two options are used for this scope, and are:
#
# * cluster-announce-ip
# * cluster-announce-port
# * cluster-announce-bus-port
#
# Each instruct the node about its address, client port, and cluster message
# bus port. The information is then published in the header of the bus packets
# so that other nodes will be able to correctly map the address of the node
# publishing the information.
#
# If the above options are not used, the normal Redis Cluster auto-detection
# will be used instead.
#
# Note that when remapped, the bus port may not be at the fixed offset of
# clients port + 10000, so you can specify any port and bus-port depending
# on how they get remapped. If the bus-port is not set, a fixed offset of
# 10000 will be used as usually.
#
# Example:
#
# cluster-announce-ip 10.1.1.5
# cluster-announce-port 6379
# cluster-announce-bus-port 6380
################################## SLOW LOG ###################################
# The Redis Slow Log is a system to log queries that exceeded a specified
# execution time. The execution time does not include the I/O operations
# like talking with the client, sending the reply and so forth,
# but just the time needed to actually execute the command (this is the only
# stage of command execution where the thread is blocked and can not serve
# other requests in the meantime).
#
# You can configure the slow log with two parameters: one tells Redis
# what is the execution time, in microseconds, to exceed in order for the
# command to get logged, and the other parameter is the length of the
# slow log. When a new command is logged the oldest one is removed from the
# queue of logged commands.
# The following time is expressed in microseconds, so 1000000 is equivalent
# to one second. Note that a negative number disables the slow log, while
# a value of zero forces the logging of every command.
slowlog-log-slower-than 10000
# There is no limit to this length. Just be aware that it will consume memory.
# You can reclaim memory used by the slow log with SLOWLOG RESET.
slowlog-max-len 128
################################ LATENCY MONITOR ##############################
# The Redis latency monitoring subsystem samples different operations
# at runtime in order to collect data related to possible sources of
# latency of a Redis instance.
#
# Via the LATENCY command this information is available to the user that can
# print graphs and obtain reports.
#
# The system only logs operations that were performed in a time equal or
# greater than the amount of milliseconds specified via the
# latency-monitor-threshold configuration directive. When its value is set
# to zero, the latency monitor is turned off.
#
# By default latency monitoring is disabled since it is mostly not needed
# if you don't have latency issues, and collecting data has a performance
# impact, that while very small, can be measured under big load. Latency
# monitoring can easily be enabled at runtime using the command
# "CONFIG SET latency-monitor-threshold <milliseconds>" if needed.
latency-monitor-threshold 0
############################# EVENT NOTIFICATION ##############################
# Redis can notify Pub/Sub clients about events happening in the key space.
# This feature is documented at http://redis.io/topics/notifications
#
# For instance if keyspace events notification is enabled, and a client
# performs a DEL operation on key "foo" stored in the Database 0, two
# messages will be published via Pub/Sub:
#
# PUBLISH __keyspace@0__:foo del
# PUBLISH __keyevent@0__:del foo
#
# It is possible to select the events that Redis will notify among a set
# of classes. Every class is identified by a single character:
#
# K Keyspace events, published with __keyspace@<db>__ prefix.
# E Keyevent events, published with __keyevent@<db>__ prefix.
# g Generic commands (non-type specific) like DEL, EXPIRE, RENAME, ...
# $ String commands
# l List commands
# s Set commands
# h Hash commands
# z Sorted set commands
# x Expired events (events generated every time a key expires)
# e Evicted events (events generated when a key is evicted for maxmemory)
# A Alias for g$lshzxe, so that the "AKE" string means all the events.
#
# The "notify-keyspace-events" takes as argument a string that is composed
# of zero or multiple characters. The empty string means that notifications
# are disabled.
#
# Example: to enable list and generic events, from the point of view of the
# event name, use:
#
# notify-keyspace-events Elg
#
# Example 2: to get the stream of the expired keys subscribing to channel
# name __keyevent@0__:expired use:
#
# notify-keyspace-events Ex
#
# By default all notifications are disabled because most users don't need
# this feature and the feature has some overhead. Note that if you don't
# specify at least one of K or E, no events will be delivered.
notify-keyspace-events ""
############################### ADVANCED CONFIG ###############################
# 指定在超过一定数据或者最大的元素超过某一临界值时,采用如下特殊哈希算法,未超过则使用ziplist
hash-max-ziplist-entries 512
hash-max-ziplist-value 64
# Lists are also encoded in a special way to save a lot of space.
# The number of entries allowed per internal list node can be specified
# as a fixed maximum size or a maximum number of elements.
# For a fixed maximum size, use -5 through -1, meaning:
# -5: max size: 64 Kb <-- not recommended for normal workloads
# -4: max size: 32 Kb <-- not recommended
# -3: max size: 16 Kb <-- probably not recommended
# -2: max size: 8 Kb <-- good
# -1: max size: 4 Kb <-- good
# Positive numbers mean store up to _exactly_ that number of elements
# per list node.
# The highest performing option is usually -2 (8 Kb size) or -1 (4 Kb size),
# but if your use case is unique, adjust the settings as necessary.
list-max-ziplist-size -2
# Lists may also be compressed.
# Compress depth is the number of quicklist ziplist nodes from *each* side of
# the list to *exclude* from compression. The head and tail of the list
# are always uncompressed for fast push/pop operations. Settings are:
# 0: disable all list compression
# 1: depth 1 means "don't start compressing until after 1 node into the list,
# going from either the head or tail"
# So: [head]->node->node->...->node->[tail]
# [head], [tail] will always be uncompressed; inner nodes will compress.
# 2: [head]->[next]->node->node->...->node->[prev]->[tail]
# 2 here means: don't compress head or head->next or tail->prev or tail,
# but compress all nodes between them.
# 3: [head]->[next]->[next]->node->node->...->node->[prev]->[prev]->[tail]
# etc.
list-compress-depth 0
# Sets have a special encoding in just one case: when a set is composed
# of just strings that happen to be integers in radix 10 in the range
# of 64 bit signed integers.
# The following configuration setting sets the limit in the size of the
# set in order to use this special memory saving encoding.
set-max-intset-entries 512
# Similarly to hashes and lists, sorted sets are also specially encoded in
# order to save a lot of space. This encoding is only used when the length and
# elements of a sorted set are below the following limits:
zset-max-ziplist-entries 128
zset-max-ziplist-value 64
# HyperLogLog sparse representation bytes limit. The limit includes the
# 16 bytes header. When an HyperLogLog using the sparse representation crosses
# this limit, it is converted into the dense representation.
#
# A value greater than 16000 is totally useless, since at that point the
# dense representation is more memory efficient.
#
# The suggested value is ~ 3000 in order to have the benefits of
# the space efficient encoding without slowing down too much PFADD,
# which is O(N) with the sparse encoding. The value can be raised to
# ~ 10000 when CPU is not a concern, but space is, and the data set is
# composed of many HyperLogLogs with cardinality in the 0 - 15000 range.
hll-sparse-max-bytes 3000
# Streams macro node max size / items. The stream data structure is a radix
# tree of big nodes that encode multiple items inside. Using this configuration
# it is possible to configure how big a single node can be in bytes, and the
# maximum number of items it may contain before switching to a new node when
# appending new stream entries. If any of the following settings are set to
# zero, the limit is ignored, so for instance it is possible to set just a
# max entires limit by setting max-bytes to 0 and max-entries to the desired
# value.
stream-node-max-bytes 4096
stream-node-max-entries 100
# 指定是否激活重置哈希,默认为开启。对实时性要求高的,可更改为no,不开启
activerehashing yes
# The client output buffer limits can be used to force disconnection of clients
# that are not reading data from the server fast enough for some reason (a
# common reason is that a Pub/Sub client can't consume messages as fast as the
# publisher can produce them).
#
# The limit can be set differently for the three different classes of clients:
#
# normal -> normal clients including MONITOR clients
# replica -> replica clients
# pubsub -> clients subscribed to at least one pubsub channel or pattern
#
# The syntax of every client-output-buffer-limit directive is the following:
#
# client-output-buffer-limit <class> <hard limit> <soft limit> <soft seconds>
#
# A client is immediately disconnected once the hard limit is reached, or if
# the soft limit is reached and remains reached for the specified number of
# seconds (continuously).
# So for instance if the hard limit is 32 megabytes and the soft limit is
# 16 megabytes / 10 seconds, the client will get disconnected immediately
# if the size of the output buffers reach 32 megabytes, but will also get
# disconnected if the client reaches 16 megabytes and continuously overcomes
# the limit for 10 seconds.
#
# By default normal clients are not limited because they don't receive data
# without asking (in a push way), but just after a request, so only
# asynchronous clients may create a scenario where data is requested faster
# than it can read.
#
# Instead there is a default limit for pubsub and replica clients, since
# subscribers and replicas receive data in a push fashion.
#
# Both the hard or the soft limit can be disabled by setting them to zero.
client-output-buffer-limit normal 0 0 0
client-output-buffer-limit replica 256mb 64mb 60
client-output-buffer-limit pubsub 32mb 8mb 60
# Client query buffers accumulate new commands. They are limited to a fixed
# amount by default in order to avoid that a protocol desynchronization (for
# instance due to a bug in the client) will lead to unbound memory usage in
# the query buffer. However you can configure it here if you have very special
# needs, such us huge multi/exec requests or alike.
#
# client-query-buffer-limit 1gb
# In the Redis protocol, bulk requests, that are, elements representing single
# strings, are normally limited ot 512 mb. However you can change this limit
# here.
#
# proto-max-bulk-len 512mb
# Redis calls an internal function to perform many background tasks, like
# closing connections of clients in timeout, purging expired keys that are
# never requested, and so forth.
#
# Not all tasks are performed with the same frequency, but Redis checks for
# tasks to perform according to the specified "hz" value.
#
# By default "hz" is set to 10. Raising the value will use more CPU when
# Redis is idle, but at the same time will make Redis more responsive when
# there are many keys expiring at the same time, and timeouts may be
# handled with more precision.
#
# The range is between 1 and 500, however a value over 100 is usually not
# a good idea. Most users should use the default of 10 and raise this up to
# 100 only in environments where very low latency is required.
hz 10
# Normally it is useful to have an HZ value which is proportional to the
# number of clients connected. This is useful in order, for instance, to
# avoid too many clients are processed for each background task invocation
# in order to avoid latency spikes.
#
# Since the default HZ value by default is conservatively set to 10, Redis
# offers, and enables by default, the ability to use an adaptive HZ value
# which will temporary raise when there are many connected clients.
#
# When dynamic HZ is enabled, the actual configured HZ will be used as
# as a baseline, but multiples of the configured HZ value will be actually
# used as needed once more clients are connected. In this way an idle
# instance will use very little CPU time while a busy instance will be
# more responsive.
dynamic-hz yes
# When a child rewrites the AOF file, if the following option is enabled
# the file will be fsync-ed every 32 MB of data generated. This is useful
# in order to commit the file to the disk more incrementally and avoid
# big latency spikes.
aof-rewrite-incremental-fsync yes
# When redis saves RDB file, if the following option is enabled
# the file will be fsync-ed every 32 MB of data generated. This is useful
# in order to commit the file to the disk more incrementally and avoid
# big latency spikes.
rdb-save-incremental-fsync yes
# Redis LFU eviction (see maxmemory setting) can be tuned. However it is a good
# idea to start with the default settings and only change them after investigating
# how to improve the performances and how the keys LFU change over time, which
# is possible to inspect via the OBJECT FREQ command.
#
# There are two tunable parameters in the Redis LFU implementation: the
# counter logarithm factor and the counter decay time. It is important to
# understand what the two parameters mean before changing them.
#
# The LFU counter is just 8 bits per key, it's maximum value is 255, so Redis
# uses a probabilistic increment with logarithmic behavior. Given the value
# of the old counter, when a key is accessed, the counter is incremented in
# this way:
#
# 1. A random number R between 0 and 1 is extracted.
# 2. A probability P is calculated as 1/(old_value*lfu_log_factor+1).
# 3. The counter is incremented only if R < P.
#
# The default lfu-log-factor is 10. This is a table of how the frequency
# counter changes with a different number of accesses with different
# logarithmic factors:
#
# +--------+------------+------------+------------+------------+------------+
# | factor | 100 hits | 1000 hits | 100K hits | 1M hits | 10M hits |
# +--------+------------+------------+------------+------------+------------+
# | 0 | 104 | 255 | 255 | 255 | 255 |
# +--------+------------+------------+------------+------------+------------+
# | 1 | 18 | 49 | 255 | 255 | 255 |
# +--------+------------+------------+------------+------------+------------+
# | 10 | 10 | 18 | 142 | 255 | 255 |
# +--------+------------+------------+------------+------------+------------+
# | 100 | 8 | 11 | 49 | 143 | 255 |
# +--------+------------+------------+------------+------------+------------+
#
# NOTE: The above table was obtained by running the following commands:
#
# redis-benchmark -n 1000000 incr foo
# redis-cli object freq foo
#
# NOTE 2: The counter initial value is 5 in order to give new objects a chance
# to accumulate hits.
#
# The counter decay time is the time, in minutes, that must elapse in order
# for the key counter to be divided by two (or decremented if it has a value
# less <= 10).
#
# The default value for the lfu-decay-time is 1. A Special value of 0 means to
# decay the counter every time it happens to be scanned.
#
# lfu-log-factor 10
# lfu-decay-time 1
########################### ACTIVE DEFRAGMENTATION #######################
#
# WARNING THIS FEATURE IS EXPERIMENTAL. However it was stress tested
# even in production and manually tested by multiple engineers for some
# time.
#
# What is active defragmentation?
# -------------------------------
#
# Active (online) defragmentation allows a Redis server to compact the
# spaces left between small allocations and deallocations of data in memory,
# thus allowing to reclaim back memory.
#
# Fragmentation is a natural process that happens with every allocator (but
# less so with Jemalloc, fortunately) and certain workloads. Normally a server
# restart is needed in order to lower the fragmentation, or at least to flush
# away all the data and create it again. However thanks to this feature
# implemented by Oran Agra for Redis 4.0 this process can happen at runtime
# in an "hot" way, while the server is running.
#
# Basically when the fragmentation is over a certain level (see the
# configuration options below) Redis will start to create new copies of the
# values in contiguous memory regions by exploiting certain specific Jemalloc
# features (in order to understand if an allocation is causing fragmentation
# and to allocate it in a better place), and at the same time, will release the
# old copies of the data. This process, repeated incrementally for all the keys
# will cause the fragmentation to drop back to normal values.
#
# Important things to understand:
#
# 1. This feature is disabled by default, and only works if you compiled Redis
# to use the copy of Jemalloc we ship with the source code of Redis.
# This is the default with Linux builds.
#
# 2. You never need to enable this feature if you don't have fragmentation
# issues.
#
# 3. Once you experience fragmentation, you can enable this feature when
# needed with the command "CONFIG SET activedefrag yes".
#
# The configuration parameters are able to fine tune the behavior of the
# defragmentation process. If you are not sure about what they mean it is
# a good idea to leave the defaults untouched.
# Enabled active defragmentation
# activedefrag yes
# Minimum amount of fragmentation waste to start active defrag
# active-defrag-ignore-bytes 100mb
# Minimum percentage of fragmentation to start active defrag
# active-defrag-threshold-lower 10
# Maximum percentage of fragmentation at which we use maximum effort
# active-defrag-threshold-upper 100
# Minimal effort for defrag in CPU percentage
# active-defrag-cycle-min 5
# Maximal effort for defrag in CPU percentage
# active-defrag-cycle-max 75
# Maximum number of set/hash/zset/list fields that will be processed from
# the main dictionary scan
# active-defrag-max-scan-fields 1000