【redis的学习与使用】

食用级别:初级 & 中级

学习视频:狂神

redis定义与介绍:

Redis基于内存运行并支持持久化的NoSQL数据库,也被称为数据结构服务器

string 是 redis 最基本的类型,一个 key 对应一个 value。

string 类型是二进制安全的。意思是 redis 的 string 可以包含任何数据。比如jpg图片或者序列化的对象。

string 类型是 Redis 最基本的数据类型,string 类型的值最大能存储 512MB。

Redis默认使用6379通信端口。

redis特点:

  • 性能优秀,数据在内存中,读写速度非常快,支持并发 10W QPS。

  • 单进程单线程,是线程安全的,采用 IO 多路复用机制。

  • 丰富的数据类型,支持字符串(strings)、散列/哈希(hashes)、列表(lists)、集合(sets)、有序集合zset(sorted sets)等。

  • 支持数据持久化。

    可以将内存中数据保存在磁盘中,重启时加载。

  • 主从复制,哨兵,高可用。

  • 可以用作分布式锁。

  • 可以作为消息中间件使用,支持发布订阅。

参考:https://www.cnblogs.com/it-deepinmind/p/14252804.html

为什么可以用redis作为mysql的缓存配合使用:

因为mysql存储在磁盘里,redis存储在内存里,redis既可以用来做持久存储,也可以做缓存,而目前大多数公司的存储都是mysql + redis,mysql作为主存储,redis作为辅助存储被用作缓存,加快访问读取的速度,提高性能

(个人理解:组原里应该提过,内存的读取速度是远远快于磁盘的,但是全用内存又成本太高,所以采用这样一种内外结合的方式,需要注重性能的地方使用redis,不需要的用mysql即可)

这同样解释了为什么redis不使用多线程(不过现在的redis6已结开始支持多线程了),它是基于内存操作的,和CPU没有什么关系,多线程也不会让其效率得到提升,可能还会出现各种问题。

至于它为什么这么快:一个是语言原因,redis是C开发的,C的速度很快,一个就是没有多线程导致的复杂处理情景

redis6.0——新特性之一:多线程

  • redis6多线程只是用来处理网络数据的读写和协议解析上,底层数据操作还是单线程

  • 执行命令仍然是单线程,之所以这么设计是不想因为多线程而变得复杂,需要去控制key、lua、事务、LPUSH/LPOP等等的并发问题

  • 官网上提到,某场景下使用多线程可以提高一倍的效率(自身没有用到redis6,所以只是提一句,redis6的特性来源网络,好多一样的,我也不知道谁参考谁。。)

为什么要用redis:

这个主要是要考虑性能和并发,高并发下,大量请求访问(冲击)数据库,会导致访问异常,redis可以作为缓冲。还有上面说的,整体上可以拉高一些读取速度。

另外redis还可以作为消息中间件(消息发布与订阅等等)

总结来说:三个作用:缓存,数据库,中间件

redis的一些命令行操作:

java的redis缓存操作其实也和命令行大同小异,这里先了解一下命令行下的各种操作:

redis默认有16个数据库,一般都会默认存在第一个数据库,我们可以通过select来切换数据库

 keys *  操作查看当前所有的key,比如3库中的"name",然后可以通过get name 来获取“name”的value值

清空操作:flushall或者flushdb,注意,这些是清空数据库而不是界面,,和mysql很不一样的(当然大部分人都没有相关的权限,不然.....)

EXISTS name   如果key存在则返回1

move name     移除key

 利用expire设置KEY过期时间 ,10s ,ttl可查看剩余时间;

type name 查看key【name】的数据类型

 setex 可以设置键值并同时设置key的过期时间

 mset可以批量创建;同理,mget可以批量获取keys;

setnx:与set不同的是,setnx k1 v1 的时候若k1已经存在则报错,不存在则正常创建;

msetnx:批量创建,具有原子性,也就是一致性,比方说,msetnx k1 v1 k4 v4 其中k1已存在,k4不存在,所以批量创建会失败,只要有一个已存在就会整体失败。

 

 getset操作:先查询后更新,查不到会返回null,但是更新操作会生效,如上图;

除了String类型,List,set,hash,zset 这四种类型是最常用的:

【List】

 redis中list 可以左插入或是右插入(类似于队列),比如 有这样一排座位,只从左侧开始,1号队友先坐了左数第一个座位,但是一会儿二号又来了,没办法,1号只能往右边挪一个位置,所以这样子,如图,list 中最左边的元素应该是最后一个插入的;Pop操作也很好理解,可以左右出列 。同样,右插,rpush同理(注意,是没有rrange这种东西的);

lindex 操作 获取list中的某个特定下标对应的元素

 

 Llen list 操作 #获取list长度

删除特定的值:

  List与set不同,是可以允许重复值存在的,所以利用 lrem 可以移除多个value

 图中数字很多,可能没有辨识度,但是当你输入的时候redis会有提示的,比如:

 如图,我remove了两个特定value“3”,精确匹配

trim 截取操作, 如图,我截取了0到1 ,即前两个值(左数)

 ropolpush  list otherlist   移除list的最后一个元素(最右),存入一个新list中

同样的,如果列表下标存在值,可以对此下标进行 lset操作 ,进行value更新;

    可以通过  linsert  来实现插入,通过before和after来控制插入位置

 【set】

set里面的插入操作为sadd

查询集合成员:smembers

取交集 sdiff  ;   取并集 sunion;

 

【hash】

和String操作类似,只不过用K-V取代了V

hset 添加

hget 获取

hmset  set多个k-v

hmget  get多个k-v

hgetall  获取所有

hdel   删除指定的hash key(对应的value会自动被删除)

hkeys   获取所有的keys

hvals    获取所有的values

【zset】即sortset

 同set,有zadd

以及有序排列

 当元素存在时zadd则起到更新的作用;

 这里面zrangebyscore 的score是redis自带的 

 

 也可以限定范围进行排序

【geospatial地理位置】

  同时geo也是一种特殊数据类型。

  通过geoadd可以给一个key添加多个位置节点(注意是先经度后维度)

  利用geodist:计算两个位置节点之间的距离

  georadius:根据用户给定的经纬度坐标来获取指定范围内的地理位置集合,注意距离 10 km 的数字和单位中间间隔一个空格

  geopos 用于从给定的 key 里返回所有指定名称(member)的位置(经度和纬度),不存在的返回 nil。

  georadius 以给定的经纬度为中心, 返回键包含的位置元素当中, 与中心的距离不超过给定最大距离的所有位置元素。

  georadiusbymember 和 GEORADIUS 命令一样, 都可以找出位于指定范围内的元素, 但是 georadiusbymember 的中心点是由给定的位置元素决定的, 而不是使用经度和纬度来决定中心点。

  geohash:返回一个或多个位置对象的 geohash 值。

  测试demo如下:

[root@iZbp1hwh629hd4xz80i1z0Z bin]# redis-cli -p 6379
127.0.0.1:6379> geoadd china:city 116.9038723847656 39.66750041446214 beijing
(integer) 1
127.0.0.1:6379> geoadd china:city 91.13775 29.65262 lasa
(integer) 1
127.0.0.1:6379> geodist testkey beijing lasa
(nil)
127.0.0.1:6379> geoadd testkey  116.9038723847656 39.66750041446214 beijing
(integer) 1
127.0.0.1:6379> geoadd testkey  91.13775 29.65262 lasa
(integer) 1
127.0.0.1:6379> geodist testkey beijing lasa
"2594695.6553"
127.0.0.1:6379> georadius testkey 116 39 10km
(error) ERR wrong number of arguments for 'georadius' command
127.0.0.1:6379> georadius testkey 116 39 100km
(error) ERR wrong number of arguments for 'georadius' command
127.0.0.1:6379> georadius testkey 116 39 10 km
(empty list or set)
127.0.0.1:6379> georadius testkey 116 39 100 km withdist
(empty list or set)
127.0.0.1:6379> geoadd testkey  117 39 tianjin
(integer) 1
127.0.0.1:6379> geodist testkey beijing tianjin
"74702.7948"
127.0.0.1:6379> georadius testkey 117 39 10 km withdist
1) 1) "tianjin"
   2) "0.0002"
127.0.0.1:6379> georadius testkey 117 39 100 km withdist
1) 1) "tianjin"
   2) "0.0002"
2) 1) "beijing"
   2) "74.7027"
127.0.0.1:6379> georadius testkey 117 39 20 km withdist
1) 1) "tianjin"
   2) "0.0002"
127.0.0.1:6379> geopos testkey beijing nonexisting
1) 1) "116.90387338399887085"
   2) "39.66750025860940099"
2) (nil)
127.0.0.1:6379> georadius testkey 117 38.8 20 km withdist
(empty list or set)
127.0.0.1:6379> georadius testkey 117 38.8 200 km withdist
1) 1) "tianjin"
   2) "22.2452"
2) 1) "beijing"
   2) "96.8436"
127.0.0.1:6379> georadiusbymember testkey beijing  200 km withdist
1) 1) "tianjin"
   2) "74.7028"
2) 1) "beijing"
   2) "0.0000"
127.0.0.1:6379> geohash testkey beijing lasa
1) "wx51sjnzcw0"
2) "wj2b9yh7p20"
127.0.0.1:6379> 

PS:根据百度地图-工具箱-测距 来计算,拉萨-北京距离为2558600米,和redis计算结果2594695.6553,大致相同,数据不同可能是坐标原点取值不同?

  

【Hyperloglog——统计基数利器】

   Hyperloglog也是一种特殊的数据类型。

   适用于需要计算大量不同特征数据个数的需求,比如统计 不同用户访问网站,多个人访问同一个网站,只需要计入一次;传统方法是利用set存储统计,而Hyperloglog 的优势就是不存储,只计算,这样就节省了很多内存空间。

  测试代码:

127.0.0.1:6379> pfadd pfkey zoe louis nick coach zoey zoe
(integer) 1
127.0.0.1:6379> pfcount pfkey
(integer) 5
127.0.0.1:6379> 

【Bitmap】 

  一种redis 的特殊数据类型。

  是用0,1二进制对立方式来存储记录的,例如记录 一周内的打卡与否:

  示例如下:

127.0.0.1:6379> setbit bitkey 1  1
(integer) 0
127.0.0.1:6379> setbit bitkey 2 0
(integer) 0
127.0.0.1:6379> setbit bitkey 3 1
(integer) 0
127.0.0.1:6379> setbit bitkey 4 1
(integer) 0
127.0.0.1:6379> getbit bitkey 3
(integer) 1
127.0.0.1:6379> bitcount bitkey 
(integer) 3
127.0.0.1:6379> bitcount bitkey 1 3
(integer) 0
127.0.0.1:6379> bitcount bitkey [1 3]
(error) ERR value is not an integer or out of range
127.0.0.1:6379> bitcount bitkey 1 3
(integer) 0
127.0.0.1:6379> bitcount bitkey 0 2
(integer) 3
127.0.0.1:6379> bitcount bitkey 1 2
(integer) 0
127.0.0.1:6379> 

  值得注意的是,bitcount 指令是统计字节数组中对应1的个数,拿上面bitkey中的数据为例,目前下标 0,1,2,3 四个位置上存有数据,

  第一个元素存储是1,即 对应 01000000 (除去第一位后的第一个置为1),1,2,3同理,存储后如下:01011000 。

  所谓 指令 bitcount bitkey 1 3 ,是统计 01011000  00000000 00000000 00000000 这四个部分对应 第二个到第四个有多少个1 ,结果是0;

  而  bitcount bitkey 0 2, 是统计 上面四个中的前三个  01011000  00000000 00000000 有几个1, 结果是 3个;

  当然,就结果而言,可以理解为 使用bitcount keyname 可直接统计内存中元素为1 的个数。

【redis的基本事务操作】

   redis一个事务可以一次执行多个命令,或者说是一组,然后这一组命令都会被序列化,事务执行过程中,命令会顺序执行(exec前均不会执行)。

  其有如下三个性质:

  • 批量操作在发送 EXEC 命令前被放入队列缓存。
  • 收到 EXEC 命令后进入事务执行,事务中任意命令执行失败,其余的命令依然被执行(且无回滚操作)。
  • 在事务执行过程,其他客户端提交的命令请求不会插入到事务执行命令序列中。

  

  PS:单个 Redis 命令的执行是原子性的,但 Redis 没有在事务上增加任何维持原子性的机制,所以 Redis 事务的执行并不是原子性的,事务可以理解为一个打包的批量执行脚本,但批量指令并非原子化的操作,中间某条指令的失败不会导致前面已做指令的回滚,也不会造成后续的指令不做。

  (数据库事务的原子性:一个事务包含多个操作,这些操作要么全部执行,要么全都不执行。实现事务的原子性,要支持回滚操作,在某个操作失败后,回滚到事务执行之前的状态,也就是说)。

    PS: redis事务也木有隔离级别的概念,(也就是没有数据脏读,重复读,幻读等危险),因为这一些列命令都是顺序执行的,而且 执行事务EXEC 这个操作后 才会依次执行这一组命令。

  redis 事务命令:

  • multi :事务开始
  • 命令入队
  • exec:事务执行

  测试:

127.0.0.1:6379> multi
OK
127.0.0.1:6379> set l4d1 zoey
QUEUED
127.0.0.1:6379> set l4d3 rochelle
QUEUED
127.0.0.1:6379> get l4d3
QUEUED
127.0.0.1:6379> set l4d4 zoe
QUEUED
127.0.0.1:6379> exec
1) OK
2) OK
3) "rochelle"
4) OK
127.0.0.1:6379> 

#取消事务执行

127.0.0.1:6379> multi
OK
127.0.0.1:6379> set k1 v1
QUEUED
127.0.0.1:6379> discard
OK
127.0.0.1:6379>

注意:在事务中输入命令队列时如果出现 编译型异常,会导致exec时全部命令无法执行;而语法错误,比如对字符串进行加减操作时,只是错误语句无法执行而已:

实例:

127.0.0.1:6379> flushdb
OK
127.0.0.1:6379> clear
127.0.0.1:6379> set k1 "wang"
OK
127.0.0.1:6379> multi
OK
127.0.0.1:6379> incr k1
QUEUED
127.0.0.1:6379> set k2 v2
QUEUED
127.0.0.1:6379> get k2
QUEUED
127.0.0.1:6379> exec
1) (error) ERR value is not an integer or out of range
2) OK
3) "v2"
127.0.0.1:6379> 

【乐观锁与悲观锁】

   乐观锁:默认认为不会出现问题,不加锁,会在更新数据时区判断一下此期间数据是否有人修改

   悲观锁:过于悲观,认为总有刁民要造反,无论什么行为都会加锁,此举大大影响性能

  redis采用watch 命令来监控事务数据,当事务执行完成后监控会自动取消:

  测试案例:

  开启两个命令行窗口模仿并行操作:

  如果开启监控watch后(可以通过unwatch解锁),执行事务前,通过另一个窗口(线程)去对监控变量进行操作变更,那么原窗口执行事务时就会出现错误,无法执行事务内命令。

  

 最后,倘若事务执行失败,就先进行解锁,然后再加锁(watch)监控,然后开启事务,观察加减操作后(比如+1-1)变量值是否还是监控时的值,若相同,肯定是可以执行成功的。

redis在linux的benchmark 测试【压力测试】

redis-server kconfig/redis.conf    #开启服务

redis-cli -p 6379  #然后建立连接

进入redis相关目录下

 运行:redis-benchmark -h localhost -p 6379 -c 100 -n 100000 -t set        是特指测试set命令

redis-benchmark -h localhost -p 6379 -c 100 -n 100000           是测试全部命令,get、set、incr、lpush等

 测试结果数据:

====== SET ======
100000 requests completed in 2.10 seconds
100 parallel clients      #100个并发客户端
3 bytes payload       #每次写入3个字节
keep alive: 1        #一台服务器处理(单机性能)

12.59% <= 1 milliseconds
93.36% <= 2 milliseconds
99.42% <= 3 milliseconds
99.54% <= 8 milliseconds
99.55% <= 9 milliseconds
99.57% <= 11 milliseconds
99.60% <= 12 milliseconds
99.82% <= 13 milliseconds
99.95% <= 14 milliseconds
99.95% <= 15 milliseconds
99.97% <= 16 milliseconds
100.00% <= 16 milliseconds    
47596.38 requests per second   //10w条请求用时 2.1s左右,平均 每秒处理47596.38 条请求


[root@iZbp1hwh629hd4xz80i1z0Z bin]# redis-benchmark -h localhost -p 6379 -c 100 -n 100000
====== PING_INLINE ======
100000 requests completed in 2.12 seconds
100 parallel clients
3 bytes payload
keep alive: 1

12.79% <= 1 milliseconds
92.15% <= 2 milliseconds
99.29% <= 3 milliseconds
99.37% <= 4 milliseconds
99.38% <= 6 milliseconds
99.43% <= 7 milliseconds
99.51% <= 8 milliseconds
99.52% <= 9 milliseconds
99.60% <= 11 milliseconds
99.62% <= 12 milliseconds
99.79% <= 13 milliseconds
99.90% <= 23 milliseconds
99.92% <= 24 milliseconds
100.00% <= 25 milliseconds
47103.16 requests per second

====== PING_BULK ======
100000 requests completed in 2.06 seconds
100 parallel clients
3 bytes payload
keep alive: 1

16.59% <= 1 milliseconds
94.58% <= 2 milliseconds
99.16% <= 3 milliseconds
99.36% <= 4 milliseconds
99.39% <= 6 milliseconds
99.41% <= 7 milliseconds
99.49% <= 9 milliseconds
99.55% <= 10 milliseconds
99.57% <= 11 milliseconds
99.58% <= 12 milliseconds
99.83% <= 13 milliseconds
99.90% <= 18 milliseconds
99.95% <= 19 milliseconds
100.00% <= 19 milliseconds
48496.61 requests per second

====== SET ======
100000 requests completed in 2.12 seconds
100 parallel clients
3 bytes payload
keep alive: 1

13.89% <= 1 milliseconds
93.75% <= 2 milliseconds
99.59% <= 3 milliseconds
99.62% <= 12 milliseconds
99.78% <= 13 milliseconds
99.96% <= 18 milliseconds
99.98% <= 40 milliseconds
100.00% <= 41 milliseconds
100.00% <= 41 milliseconds
47214.35 requests per second

====== GET ======
100000 requests completed in 1.95 seconds
100 parallel clients
3 bytes payload
keep alive: 1

20.61% <= 1 milliseconds
97.57% <= 2 milliseconds
99.48% <= 3 milliseconds
99.51% <= 4 milliseconds
99.51% <= 7 milliseconds
99.57% <= 8 milliseconds
99.61% <= 11 milliseconds
99.64% <= 12 milliseconds
99.74% <= 13 milliseconds
99.86% <= 14 milliseconds
99.93% <= 18 milliseconds
100.00% <= 18 milliseconds
51282.05 requests per second

====== INCR ======
100000 requests completed in 2.10 seconds
100 parallel clients
3 bytes payload
keep alive: 1

14.50% <= 1 milliseconds
91.14% <= 2 milliseconds
99.37% <= 3 milliseconds
99.47% <= 4 milliseconds
99.50% <= 5 milliseconds
99.54% <= 7 milliseconds
99.60% <= 10 milliseconds
99.62% <= 11 milliseconds
99.62% <= 12 milliseconds
99.79% <= 13 milliseconds
99.81% <= 18 milliseconds
99.85% <= 19 milliseconds
99.90% <= 20 milliseconds
99.97% <= 21 milliseconds
100.00% <= 21 milliseconds
47528.52 requests per second

====== LPUSH ======
100000 requests completed in 2.21 seconds
100 parallel clients
3 bytes payload
keep alive: 1

9.98% <= 1 milliseconds
88.18% <= 2 milliseconds
99.11% <= 3 milliseconds
99.24% <= 7 milliseconds
99.27% <= 8 milliseconds
99.41% <= 9 milliseconds
99.44% <= 11 milliseconds
99.45% <= 12 milliseconds
99.67% <= 13 milliseconds
99.90% <= 19 milliseconds
99.91% <= 20 milliseconds
99.97% <= 21 milliseconds
100.00% <= 21 milliseconds
45269.35 requests per second

====== RPUSH ======
100000 requests completed in 2.02 seconds
100 parallel clients
3 bytes payload
keep alive: 1

15.92% <= 1 milliseconds
96.00% <= 2 milliseconds
99.51% <= 3 milliseconds
99.66% <= 4 milliseconds
99.70% <= 5 milliseconds
99.75% <= 6 milliseconds
99.76% <= 7 milliseconds
99.80% <= 10 milliseconds
99.80% <= 12 milliseconds
99.92% <= 13 milliseconds
99.98% <= 15 milliseconds
100.00% <= 15 milliseconds
49627.79 requests per second

====== LPOP ======
100000 requests completed in 2.00 seconds
100 parallel clients
3 bytes payload
keep alive: 1

15.61% <= 1 milliseconds
97.48% <= 2 milliseconds
99.55% <= 3 milliseconds
99.57% <= 6 milliseconds
99.60% <= 12 milliseconds
99.74% <= 13 milliseconds
99.78% <= 15 milliseconds
99.81% <= 16 milliseconds
99.95% <= 17 milliseconds
99.96% <= 18 milliseconds
100.00% <= 19 milliseconds
100.00% <= 19 milliseconds
50075.11 requests per second

====== RPOP ======
100000 requests completed in 2.09 seconds
100 parallel clients
3 bytes payload
keep alive: 1

13.32% <= 1 milliseconds
94.35% <= 2 milliseconds
99.27% <= 3 milliseconds
99.30% <= 5 milliseconds
99.32% <= 6 milliseconds
99.41% <= 7 milliseconds
99.51% <= 8 milliseconds
99.53% <= 9 milliseconds
99.53% <= 10 milliseconds
99.63% <= 11 milliseconds
99.68% <= 12 milliseconds
99.91% <= 13 milliseconds
100.00% <= 13 milliseconds
47824.00 requests per second

====== SADD ======
100000 requests completed in 2.09 seconds
100 parallel clients
3 bytes payload
keep alive: 1

12.97% <= 1 milliseconds
93.52% <= 2 milliseconds
99.49% <= 3 milliseconds
99.52% <= 4 milliseconds
99.53% <= 5 milliseconds
99.57% <= 6 milliseconds
99.63% <= 12 milliseconds
99.75% <= 13 milliseconds
99.80% <= 15 milliseconds
99.82% <= 16 milliseconds
99.90% <= 17 milliseconds
99.90% <= 21 milliseconds
99.96% <= 22 milliseconds
100.00% <= 22 milliseconds
47869.79 requests per second

====== HSET ======
100000 requests completed in 1.94 seconds
100 parallel clients
3 bytes payload
keep alive: 1

17.82% <= 1 milliseconds
98.41% <= 2 milliseconds
99.39% <= 3 milliseconds
99.41% <= 8 milliseconds
99.47% <= 9 milliseconds
99.56% <= 10 milliseconds
99.59% <= 11 milliseconds
99.62% <= 12 milliseconds
99.79% <= 13 milliseconds
99.90% <= 14 milliseconds
99.91% <= 15 milliseconds
99.99% <= 16 milliseconds
100.00% <= 16 milliseconds
51493.30 requests per second

====== SPOP ======
100000 requests completed in 2.03 seconds
100 parallel clients
3 bytes payload
keep alive: 1

16.54% <= 1 milliseconds
96.18% <= 2 milliseconds
99.56% <= 3 milliseconds
99.58% <= 4 milliseconds
99.59% <= 5 milliseconds
99.68% <= 8 milliseconds
99.68% <= 12 milliseconds
99.85% <= 13 milliseconds
99.96% <= 14 milliseconds
99.96% <= 18 milliseconds
100.00% <= 18 milliseconds
49333.99 requests per second

====== LPUSH (needed to benchmark LRANGE) ======
100000 requests completed in 2.08 seconds
100 parallel clients
3 bytes payload
keep alive: 1

13.43% <= 1 milliseconds
92.89% <= 2 milliseconds
99.31% <= 3 milliseconds
99.41% <= 4 milliseconds
99.48% <= 5 milliseconds
99.53% <= 9 milliseconds
99.54% <= 11 milliseconds
99.57% <= 12 milliseconds
99.78% <= 13 milliseconds
99.91% <= 19 milliseconds
99.98% <= 20 milliseconds
100.00% <= 21 milliseconds
48192.77 requests per second

====== LRANGE_100 (first 100 elements) ======
100000 requests completed in 3.56 seconds
100 parallel clients
3 bytes payload
keep alive: 1

0.06% <= 1 milliseconds
26.58% <= 2 milliseconds
77.57% <= 3 milliseconds
97.64% <= 4 milliseconds
99.14% <= 5 milliseconds
99.42% <= 6 milliseconds
99.50% <= 7 milliseconds
99.50% <= 13 milliseconds
99.55% <= 14 milliseconds
99.65% <= 15 milliseconds
99.70% <= 17 milliseconds
99.72% <= 18 milliseconds
99.81% <= 19 milliseconds
99.91% <= 20 milliseconds
99.99% <= 21 milliseconds
100.00% <= 21 milliseconds
28089.89 requests per second

====== LRANGE_300 (first 300 elements) ======
100000 requests completed in 7.86 seconds
100 parallel clients
3 bytes payload
keep alive: 1

0.03% <= 1 milliseconds
2.37% <= 2 milliseconds
10.40% <= 3 milliseconds
30.75% <= 4 milliseconds
50.12% <= 5 milliseconds
67.33% <= 6 milliseconds
82.46% <= 7 milliseconds
91.40% <= 8 milliseconds
95.38% <= 9 milliseconds
96.98% <= 10 milliseconds
97.60% <= 11 milliseconds
97.93% <= 12 milliseconds
98.15% <= 13 milliseconds
98.35% <= 14 milliseconds
98.55% <= 15 milliseconds
98.81% <= 16 milliseconds
99.03% <= 17 milliseconds
99.21% <= 18 milliseconds
99.37% <= 19 milliseconds
99.48% <= 20 milliseconds
99.57% <= 21 milliseconds
99.64% <= 22 milliseconds
99.73% <= 23 milliseconds
99.81% <= 24 milliseconds
99.86% <= 25 milliseconds
99.90% <= 26 milliseconds
99.94% <= 27 milliseconds
99.96% <= 28 milliseconds
99.97% <= 29 milliseconds
99.98% <= 30 milliseconds
100.00% <= 31 milliseconds
100.00% <= 31 milliseconds
12727.50 requests per second

====== LRANGE_500 (first 450 elements) ======
100000 requests completed in 10.73 seconds
100 parallel clients
3 bytes payload
keep alive: 1

0.00% <= 1 milliseconds
0.62% <= 2 milliseconds
2.95% <= 3 milliseconds
8.97% <= 4 milliseconds
23.15% <= 5 milliseconds
39.01% <= 6 milliseconds
53.01% <= 7 milliseconds
64.53% <= 8 milliseconds
75.86% <= 9 milliseconds
85.40% <= 10 milliseconds
91.68% <= 11 milliseconds
95.22% <= 12 milliseconds
96.73% <= 13 milliseconds
97.27% <= 14 milliseconds
97.53% <= 15 milliseconds
97.86% <= 16 milliseconds
98.25% <= 17 milliseconds
98.57% <= 18 milliseconds
98.83% <= 19 milliseconds
99.05% <= 20 milliseconds
99.30% <= 21 milliseconds
99.54% <= 22 milliseconds
99.72% <= 23 milliseconds
99.83% <= 24 milliseconds
99.87% <= 25 milliseconds
99.90% <= 26 milliseconds
99.93% <= 27 milliseconds
99.94% <= 31 milliseconds
99.95% <= 32 milliseconds
99.97% <= 33 milliseconds
99.98% <= 34 milliseconds
99.99% <= 35 milliseconds
100.00% <= 37 milliseconds
9319.67 requests per second

====== LRANGE_600 (first 600 elements) ======
100000 requests completed in 14.06 seconds
100 parallel clients
3 bytes payload
keep alive: 1

0.00% <= 1 milliseconds
0.29% <= 2 milliseconds
1.28% <= 3 milliseconds
3.29% <= 4 milliseconds
8.50% <= 5 milliseconds
19.00% <= 6 milliseconds
32.82% <= 7 milliseconds
46.16% <= 8 milliseconds
56.29% <= 9 milliseconds
64.70% <= 10 milliseconds
72.87% <= 11 milliseconds
80.98% <= 12 milliseconds
87.44% <= 13 milliseconds
92.01% <= 14 milliseconds
94.46% <= 15 milliseconds
95.70% <= 16 milliseconds
96.51% <= 17 milliseconds
97.17% <= 18 milliseconds
97.67% <= 19 milliseconds
98.00% <= 20 milliseconds
98.36% <= 21 milliseconds
98.71% <= 22 milliseconds
98.95% <= 23 milliseconds
99.17% <= 24 milliseconds
99.29% <= 25 milliseconds
99.37% <= 26 milliseconds
99.43% <= 27 milliseconds
99.53% <= 28 milliseconds
99.63% <= 29 milliseconds
99.72% <= 30 milliseconds
99.79% <= 31 milliseconds
99.82% <= 32 milliseconds
99.86% <= 33 milliseconds
99.87% <= 34 milliseconds
99.89% <= 35 milliseconds
99.90% <= 36 milliseconds
99.93% <= 37 milliseconds
99.96% <= 38 milliseconds
99.97% <= 39 milliseconds
99.98% <= 41 milliseconds
99.99% <= 42 milliseconds
99.99% <= 43 milliseconds
100.00% <= 43 milliseconds
7111.36 requests per second

====== MSET (10 keys) ======
100000 requests completed in 2.39 seconds
100 parallel clients
3 bytes payload
keep alive: 1

0.24% <= 1 milliseconds
76.53% <= 2 milliseconds
97.89% <= 3 milliseconds
98.92% <= 4 milliseconds
99.15% <= 5 milliseconds
99.22% <= 6 milliseconds
99.26% <= 7 milliseconds
99.27% <= 8 milliseconds
99.30% <= 9 milliseconds
99.46% <= 11 milliseconds
99.55% <= 12 milliseconds
99.65% <= 13 milliseconds
99.67% <= 14 milliseconds
99.73% <= 15 milliseconds
99.75% <= 16 milliseconds
99.86% <= 17 milliseconds
99.94% <= 23 milliseconds
99.97% <= 24 milliseconds
100.00% <= 24 milliseconds
41858.52 requests per second
View Code

在Java中的简单使用(radis缓存操作):

先交代redis支持的常用数据类型:string,set,hash,list,sortsets;

并且其可通过哨兵和自动分区提高可用性(非入门,暂时不可食用)

Java操作Redis需要jedis的jar包(当前最新以及到3.7.0了)

如果需要使用Redis连接池的话,还需commons-pool-x.x.x.jar包

现在java如果想redis整合springboot,那么基本上都是用lettuce替换jedis 

部分知识点参考:https://www.cnblogs.com/it-deepinmind/p/14252804.html

 先简单了解下Jedis :

  测试demo导入依赖:

       <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>3.3.0</version>
        </dependency>
        <!--json转换依赖 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.76</version>
        </dependency>   
     <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.2</version>
    </dependency>
    <dependency>
     <groupId>org.slf4j</groupId>
    <artifactId>slf4j-simple</artifactId>
    <version>1.7.25</version>
    <scope>compile</scope>
    </dependency>
 

  事实上在java中的命令都是我们所熟知的,在redis基础中以及学习过了:

  

  【测试连接】测试我阿里云学生机的redis是否能连接:

        Jedis jedis = new Jedis("120.26.yy.xxx",6379);
        System.out.println(jedis.ping());
        log.info("PONG~~"+jedis.ping());

如果ping操作遇到报错:Exception in thread "main" redis.clients.jedis.exceptions.JedisDataException: DENIED Redis is runnin.....

可能只是远程连接redis被拒,我们可以将受保护模式选项设置为“no”,为了让服务器开始从外部接受连接(进入redis的src目录下)

[root@iZbp1hwh629hd4xz80i1z0Z ~]# cd /usr/local/bin
[root@iZbp1hwh629hd4xz80i1z0Z bin]# ./redis-cli
127.0.0.1:6379> config set protected-mode "no"
OK
127.0.0.1:6379>

  【测试简单事务】

      //jedis.flushDB();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("gender", "female");
        jsonObject.put("name", "ZOE");
        JSONObject json = new JSONObject();
        json.put("gender","male");
        json.put("name","Ellis");
        // 开启事务
        Transaction multi = jedis.multi();
        String result = jsonObject.toJSONString();
        String resultMirror = json.toJSONString();
        // jedis.watch(result)
        try {
            multi.set("user1", result);
            multi.set("user2", resultMirror);
            // 执行事务
            multi.exec();
        }catch (Exception e){
            // 放弃事务
            multi.discard();
        } finally {
            // 关闭连接
            System.out.println(jedis.get("user1"));
            System.out.println(jedis.get("user2"));
            jedis.close();
        }

输出结果:

{"gender":"female","name":"ZOE"}
{"gender":"male","name":"Ellis"}

Springboot集成Redis 

   springboot2.x后,原来使用的 Jedis 被 lettuce ([ˈletɪs])替换(2.x内很多redis配置的相关类jedis的资源都默认不存在,所以推荐使用lettuce)。

  引入依赖:以及springboot相关依赖(略)

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <!-- https://mvnrepository.com/artifact/io.lettuce/lettuce-core -->
        <dependency>
            <groupId>io.lettuce</groupId>
            <artifactId>lettuce-core</artifactId>
            <version>6.0.2.RELEASE</version>
        </dependency>

   观察一下spring的自动配置特性:

   位置如下:

  

   请看 RedisAutoConfiguration  类,里面有两个默认的模板方法,我们可以自行重写覆盖的,方法名如下

  • RedisTemplate
  • StringRedisTemplate
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package org.springframework.boot.autoconfigure.data.redis;

import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnSingleCandidate;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;

@Configuration(
    proxyBeanMethods = false
)
@ConditionalOnClass({RedisOperations.class})
@EnableConfigurationProperties({RedisProperties.class})
@Import({LettuceConnectionConfiguration.class, JedisConnectionConfiguration.class})
public class RedisAutoConfiguration {
    public RedisAutoConfiguration() {
    }

    @Bean
    @ConditionalOnMissingBean(
        name = {"redisTemplate"}
    )
    @ConditionalOnSingleCandidate(RedisConnectionFactory.class)
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<Object, Object> template = new RedisTemplate();
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }

    @Bean
    @ConditionalOnMissingBean
    @ConditionalOnSingleCandidate(RedisConnectionFactory.class)
    public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
        StringRedisTemplate template = new StringRedisTemplate();
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }
}

测试代码:

  

@SpringBootTest
class RedisBootApplicationTests {

    @Autowired
    private RedisTemplate redisTemplate;

    @Test
    void contextLoads() {
        // redisTemplate 操作不同的数据类型,api和我们的指令是一样的
        // opsForValue 操作字符串 类似String
        // opsForList 操作List 类似List
        // opsForHah

        // 除了基本的操作,我们常用的方法都可以直接通过redisTemplate操作,比如事务和基本的CRUD

        // 获取连接对象
/*        RedisConnection connection = redisTemplate.getConnectionFactory().getConnection();
        connection.flushDb();
        connection.flushAll();*/
        //字符串类型的k-v
        redisTemplate.opsForValue().set("mylove","eggplant");
        System.out.println(redisTemplate.opsForValue().get("mylove"));

    }

}

但是我去用redis终端打开时发现木有这个key:

百度后发现原因:因为Template中set值时会先调用序列化器将键和值都序列化为byte字节数组放入redis数据库中,在客户端除非get后的key为“mylove”使用同样的序列化器序列化后的值,否则取不到值。

解决办法有两个:

  方法一:在set操作前 声明序列化类型

        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new StringRedisSerializer());

  方法二:声明模板变量时指定泛型

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

 另外,如果value是中文的话,序列化后redis终端查询时会显示奇怪的乱码:

  解决办法:启动cli时多加一个参数就行了,redis-cli --raw这种方式

如果存储对象的话建议把实体类对象转化为json传 ,代码如下:

  redisConfig:模板配置类:

package com.wang.demo.utils;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
@Configuration
public class redisConfig {
    @Bean
    @SuppressWarnings("all")
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        // 我们为了自己开发方便,一般直接使用 <String, Object>
        RedisTemplate<String, Object> template = new RedisTemplate<String,Object>();
        template.setConnectionFactory(factory);
        // Json序列化配置
        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);
        // String 的序列化
        StringRedisSerializer stringRedisSerializer = new  StringRedisSerializer();
        // key采用String的序列化方式
        template.setKeySerializer(stringRedisSerializer);
        // hash的key也采用String的序列化方式
        template.setHashKeySerializer(stringRedisSerializer);
        // value序列化方式采用jackson
        template.setValueSerializer(jackson2JsonRedisSerializer);
        // hash的value序列化方式采用jackson
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        template.afterPropertiesSet();
        return template;
    }
}

  测试类:

    @Test
    public void test()throws JsonProcessingException {
        User user = new User("克里斯",8);
        ObjectMapper mapper = new ObjectMapper();
        //调用writeValueAsString,将指定的对象转换成json
        String jsonUser = mapper.writeValueAsString(user);
        System.out.println("jsonUser"+jsonUser);
        redisTemplate.opsForValue().set("user",jsonUser);
        redisTemplate.opsForValue().set("bookName","雪中悍刀行");

        System.out.println(redisTemplate.opsForValue().get("bookName"));
        System.out.println(redisTemplate.opsForValue().get("user"));
    }

  注意User要写个对应的构造方法,不然小心value获取不到

 

redis 配置文件

  如果找不到配置文件位置,可以在根目录下使用whereis 文件名 指令

    输入vim xxx进入vim,输入a进入vim中文本编辑,按esc退出编辑,继续输入 :wq 可以退出vim回到控制台。

  PS: redis配置文件中 大小写不敏感,注意 gb和g是不一样的,类似于 1k是1000,1kb是2的10次方byte=1024 byte

   其中比较重要的一部分配置参数如下:

# Redis configuration file example.

#
#
bind 127.0.0.1 #绑定ip

protected-mode yes

# Accept connections on the specified port, default is 6379 (IANA #815344).
# If port 0 is specified Redis will not listen on a TCP socket.
port 6379

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

# 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 /tmp/redis.sock
# unixsocketperm 700

# Close the connection after a client is idle for N seconds (0 to disable)
timeout 0

# 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

################################# GENERAL #####################################

# By default Redis does not run as a daemon. Use 'yes' if you need it.
# Note that Redis will write a pid file in /var/run/redis.pid when daemonized.
daemonize yes

# If you run Redis from upstart or systemd, Redis can interact with your
# supervision tree. Options:
#   supervised no      - no supervision interaction
#   supervised upstart - signal upstart by putting Redis into SIGSTOP mode
#   supervised systemd - signal systemd by writing READY=1 to $NOTIFY_SOCKET
#   supervised auto    - detect upstart or systemd method based on
#                        UPSTART_JOB or NOTIFY_SOCKET environment variables
# Note: these supervision methods only signal "process is ready."
#       They do not enable continuous liveness pings back to your supervisor.
supervised no

# If a pid file is specified, Redis writes it where specified at startup
# and removes it at exit.
#
# When the server runs non daemonized, no pid file is created if none is
# specified in the configuration. When the server is daemonized, the pid file
# is used even if not specified, defaulting to "/var/run/redis.pid".
#
# Creating a pid file is best effort: if Redis is not able to create it
# nothing bad happens, the server will start and run normally.
pidfile /var/run/redis_6379.pid

# Specify the server verbosity level.
# This can be one of:
# debug (a lot of information, useful for development/testing)
# verbose (many rarely useful info, but not a mess like the debug level)
# notice (moderately verbose, what you want in production probably)
# warning (only very important / critical messages are logged)
loglevel notice

# Specify the log file name. Also the empty string can be used to force
# Redis to log on the standard output. Note that if you use standard
# output for logging but daemonize, logs will be sent to /dev/null
logfile ""

# 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

# Set the number of databases. The default database is DB 0, you can select
# a different one on a per-connection basis using SELECT <dbid> where
# dbid is a number between 0 and 'databases'-1
databases 16

# By default Redis shows an ASCII art logo only when started to log to the
# standard output and if the standard output is a TTY. Basically this means
# that normally a logo is displayed only in interactive sessions.
#
# However it is possible to force the pre-4.0 behavior and always show a
# ASCII art logo in startup logs by setting the following option to yes.
always-show-logo yes

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

# By default Redis will stop accepting writes if RDB snapshots are enabled
# (at least one save point) and the latest background save failed.
# This will make the user aware (in a hard way) that data is not persisting
# on disk properly, otherwise chances are that no one will notice and some
# disaster will happen.
#
# If the background saving process will start working again Redis will
# automatically allow writes again.
#
# However if you have setup your proper monitoring of the Redis server
# and persistence, you may want to disable this feature so that Redis will
# continue to work as usual even if there are problems with disk,
# permissions, and so forth.
stop-writes-on-bgsave-error yes

# Compress string objects using LZF when dump .rdb databases?
# For default that's set to 'yes' as it's almost always a win.
# If you want to save some CPU in the saving child set it to 'no' but
# the dataset will likely be bigger if you have compressible values or keys.
rdbcompression yes

# 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

# The filename where to dump the DB
dbfilename dump.rdb

# The working directory.
#
# The DB will be written inside this directory, with the filename specified
# above using the 'dbfilename' configuration directive.
#
# The Append Only File will also be created inside this directory.
#
# Note that you must specify a directory here, not a file name.
dir ./

################################# REPLICATION #################################

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

# If the master is password protected (using the "requirepass" configuration
# directive below) it is possible to tell the slave to authenticate before
# starting the replication synchronization process, otherwise the master will
# refuse the slave request.
#
# masterauth <master-password>

# When a slave loses its connection with the master, or when the replication
# is still in progress, the slave can act in two different ways:
#
# 1) if slave-serve-stale-data is set to 'yes' (the default) the slave 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 slave-serve-stale-data is set to 'no' the slave will reply with
#    an error "SYNC with master in progress" to all the kind of commands
#    but to INFO and SLAVEOF.
#
slave-serve-stale-data yes

# You can configure a slave instance to accept writes or not. Writing against
# a slave instance may be useful to store some ephemeral data (because data
# written on a slave 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 slaves are read-only.
#
# Note: read only slaves 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 slave 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 slaves using 'rename-command' to shadow all the
# administrative / dangerous commands.
slave-read-only yes

# Replication SYNC strategy: disk or socket.
#
# -------------------------------------------------------
# WARNING: DISKLESS REPLICATION IS EXPERIMENTAL CURRENTLY
# -------------------------------------------------------
#
# New slaves and reconnecting slaves 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 slaves.
# 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 slaves incrementally.
# 2) Diskless: The Redis master creates a new process that directly writes the
#              RDB file to slave sockets, without touching the disk at all.
#
# With disk-backed replication, while the RDB file is generated, more slaves
# 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 slaves 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 slaves
# 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 slaves.
#
# This is important since once the transfer starts, it is not possible to serve
# new slaves arriving, that will be queued for the next RDB transfer, so the server
# waits a delay in order to let more slaves 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

# Slaves send PINGs to server in a predefined interval. It's possible to change
# this interval with the repl_ping_slave_period option. The default value is 10
# seconds.
#
# repl-ping-slave-period 10

# The following option sets the replication timeout for:
#
# 1) Bulk transfer I/O during SYNC, from the point of view of slave.
# 2) Master timeout from the point of view of slaves (data, pings).
# 3) Slave 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-slave-period otherwise a timeout will be detected
# every time there is low traffic between the master and the slave.
#
# repl-timeout 60

# Disable TCP_NODELAY on the slave socket after SYNC?
#
# If you select "yes" Redis will use a smaller number of TCP packets and
# less bandwidth to send data to slaves. But this can add a delay for
# the data to appear on the slave side, up to 40 milliseconds with
# Linux kernels using a default configuration.
#
# If you select "no" the delay for data to appear on the slave 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 slaves 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
# slave data when slaves are disconnected for some time, so that when a slave
# wants to reconnect again, often a full resync is not needed, but a partial
# resync is enough, just passing the portion of data the slave missed while
# disconnected.
#
# The bigger the replication backlog, the longer the time the slave can be
# disconnected and later be able to perform a partial resynchronization.
#
# The backlog is only allocated once there is at least a slave connected.
#
# repl-backlog-size 1mb

# After a master has no longer connected slaves 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 slave disconnected, for
# the backlog buffer to be freed.
#
# Note that slaves never free the backlog for timeout, since they may be
# promoted to masters later, and should be able to correctly "partially
# resynchronize" with the slaves: hence they should always accumulate backlog.
#
# A value of 0 means to never release the backlog.
#
# repl-backlog-ttl 3600

# The slave priority is an integer number published by Redis in the INFO output.
# It is used by Redis Sentinel in order to select a slave to promote into a
# master if the master is no longer working correctly.
#
# A slave with a low priority number is considered better for promotion, so
# for instance if there are three slaves 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 slave as not able to perform the
# role of master, so a slave with priority of 0 will never be selected by
# Redis Sentinel for promotion.
#
# By default the priority is 100.
slave-priority 100

# It is possible for a master to stop accepting writes if there are less than
# N slaves connected, having a lag less or equal than M seconds.
#
# The N slaves 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 slave, 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 slaves
# are available, to the specified number of seconds.
#
# For example to require at least 3 slaves with a lag <= 10 seconds use:
#
# min-slaves-to-write 3
# min-slaves-max-lag 10
#
# Setting one or the other to 0 disables the feature.
#
# By default min-slaves-to-write is set to 0 (feature disabled) and
# min-slaves-max-lag is set to 10.

# A Redis master is able to list the address and port of the attached
# slaves 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 slave 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 slave is obtained
# in the following way:
#
#   IP: The address is auto detected by checking the peer address
#   of the socket used by the slave to connect with the master.
#
#   Port: The port is communicated by the slave during the replication
#   handshake, and is normally the port that the slave is using to
#   list for connections.
#
# However when port forwarding or Network Address Translation (NAT) is
# used, the slave may be actually reachable via different IP and port
# pairs. The following two options can be used by a slave 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.
#
# slave-announce-ip 5.5.5.5
# slave-announce-port 1234

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

# Command renaming.
#
# It is possible to change the name of dangerous commands in a shared
# environment. For instance the CONFIG command may be renamed into something
# hard to guess so that it will still be available for internal-use tools
# but not available for general clients.
#
# Example:
#
# rename-command CONFIG b840fc02d524045429941cc15f59e41cb7be6c52
#
# It is also possible to completely kill a command by renaming it into
# an empty string:
#
# rename-command CONFIG ""
#
# Please note that changing the name of commands that are logged into the
# AOF file or transmitted to slaves may cause problems.

################################### CLIENTS ####################################

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

############################## 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 slaves attached to an instance with maxmemory on,
# the size of the output buffers needed to feed the slaves 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 slaves 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 slaves attached it is suggested that you set a lower
# limit for maxmemory so that there is some free RAM on the system for slave
# output buffers (but this is not needed if the policy is 'noeviction').
#
# maxmemory <bytes>

# MAXMEMORY POLICY: how Redis will select what to remove when maxmemory
# is reached. You can select among five behaviors:
#
# volatile-lru -> Evict using approximated LRU among the keys with an expire set.
# allkeys-lru -> Evict any key using approximated LRU.
# volatile-lfu -> Evict using approximated LFU among the keys with an expire set.
# allkeys-lfu -> Evict any key using approximated LFU.
# volatile-random -> Remove a random key among the ones with an expire set.
# allkeys-random -> Remove a random key, any key.
# volatile-ttl -> Remove the key with the nearest expire time (minor TTL)
# noeviction -> Don't evict anything, just return an error on write operations.
#
# LRU means Least Recently Used
# LFU means Least Frequently Used
#
# Both LRU, LFU and volatile-ttl are implemented using approximated
# randomized algorithms.
#
# Note: with any of the above policies, Redis will return an error on write
#       operations, when there are no suitable keys for eviction.
#
#       At the date of writing these commands are: set setnx setex append
#       incr decr rpush lpush rpushx lpushx linsert lset rpoplpush sadd
#       sinter sinterstore sunion sunionstore sdiff sdiffstore zadd zincrby
#       zunionstore zinterstore hset hsetnx hmset hincrby incrby decrby
#       getset mset msetnx exec sort
#
# The default is:
#
# maxmemory-policy noeviction

# LRU, LFU and minimal TTL algorithms are not precise algorithms but approximated
# algorithms (in order to save memory), so you can tune it for speed or
# accuracy. For default Redis will check five keys and pick the one that was
# used less recently, you can change the sample size using the following
# configuration directive.
#
# The default of 5 produces good enough results. 10 Approximates very closely
# true LRU but costs more CPU. 3 is faster but not very accurate.
#
# maxmemory-samples 5

############################# 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 slave performs a full resynchronization with
#    its master, the content of the whole database is removed in order to
#    load the RDB file just transfered.
#
# 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
slave-lazy-flush no

############################## APPEND ONLY MODE ###############################

# By default Redis asynchronously dumps the dataset on disk. This mode is
# good enough in many applications, but an issue with the Redis process or
# a power outage may result into a few minutes of writes lost (depending on
# the configured save points).
#
# The Append Only File is an alternative persistence mode that provides
# much better durability. For instance using the default data fsync policy
# (see later in the config file) Redis can lose just one second of writes in a
# dramatic event like a server power outage, or a single write if something
# wrong with the Redis process itself happens, but the operating system is
# still running correctly.
#
# AOF and RDB persistence can be enabled at the same time without problems.
# If the AOF is enabled on startup Redis will load the AOF, that is the file
# with the better durability guarantees.
#
# Please check http://redis.io/topics/persistence for more information.

appendonly no

# The name of the append only file (default: "appendonly.aof")

appendfilename "appendonly.aof"

# The fsync() call tells the Operating System to actually write data on disk
# instead of waiting for more data in the output buffer. Some OS will really flush
# data on disk, some other OS will just try to do it ASAP.
#
# Redis supports three different modes:
#
# no: don't fsync, just let the OS flush the data when it wants. Faster.
# always: fsync after every write to the append only log. Slow, Safest.
# everysec: fsync only one time every second. Compromise.
#
# The default is "everysec", as that's usually the right compromise between
# speed and data safety. It's up to you to understand if you can relax this to
# "no" that will let the operating system flush the output buffer when
# it wants, for better performances (but if you can live with the idea of
# some data loss consider the default persistence mode that's snapshotting),
# or on the contrary, use "always" that's very slow but a bit safer than
# everysec.
#
# More details please check the following article:
# http://antirez.com/post/redis-persistence-demystified.html
#
# If unsure, use "everysec".

# appendfsync always
appendfsync everysec
# appendfsync no

# When the AOF fsync policy is set to always or everysec, and a background
# saving process (a background save or AOF log background rewriting) is
# performing a lot of I/O against the disk, in some Linux configurations
# Redis may block too long on the fsync() call. Note that there is no fix for
# this currently, as even performing fsync in a different thread will block
# our synchronous write(2) call.
#
# In order to mitigate this problem it's possible to use the following option
# that will prevent fsync() from being called in the main process while a
# BGSAVE or BGREWRITEAOF is in progress.
#
# This means that while another child is saving, the durability of Redis is
# the same as "appendfsync none". In practical terms, this means that it is
# possible to lose up to 30 seconds of log in the worst scenario (with the
# default Linux settings).
#
# If you have latency problems turn this to "yes". Otherwise leave it as
# "no" that is the safest pick from the point of view of durability.

no-appendfsync-on-rewrite no

# Automatic rewrite of the append only file.
# Redis is able to automatically rewrite the log file implicitly calling
# BGREWRITEAOF when the AOF log size grows by the specified percentage.
#
# This is how it works: Redis remembers the size of the AOF file after the
# latest rewrite (if no rewrite has happened since the restart, the size of
# the AOF at startup is used).
#
# This base size is compared to the current size. If the current size is
# bigger than the specified percentage, the rewrite is triggered. Also
# you need to specify a minimal size for the AOF file to be rewritten, this
# is useful to avoid rewriting the AOF file even if the percentage increase
# is reached but it is still pretty small.
#
# Specify a percentage of zero in order to disable the automatic AOF
# rewrite feature.

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.
#
# This is currently turned off by default in order to avoid the surprise
# of a format change, but will at some point be used as the default.
aof-use-rdb-preamble no

################################ 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 slave of a failing master will avoid to start a failover if its data
# looks too old.
#
# There is no simple way for a slave to actually have an exact measure of
# its "data age", so the following two checks are performed:
#
# 1) If there are multiple slaves able to failover, they exchange messages
#    in order to try to give an advantage to the slave with the best
#    replication offset (more data from the master processed).
#    Slaves 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 slave 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 slave will not try to failover
#    at all.
#
# The point "2" can be tuned by user. Specifically a slave will not perform
# the failover if, since the last interaction with the master, the time
# elapsed is greater than:
#
#   (node-timeout * slave-validity-factor) + repl-ping-slave-period
#
# So for example if node-timeout is 30 seconds, and the slave-validity-factor
# is 10, and assuming a default repl-ping-slave-period of 10 seconds, the
# slave will not try to failover if it was not able to talk with the master
# for longer than 310 seconds.
#
# A large slave-validity-factor may allow slaves with too old data to failover
# a master, while a too small value may prevent the cluster from being able to
# elect a slave at all.
#
# For maximum availability, it is possible to set the slave-validity-factor
# to a value of 0, which means, that slaves 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-slave-validity-factor 10

# Cluster slaves are able to migrate to orphaned masters, that are masters
# that are left without working slaves. 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 slaves.
#
# Slaves migrate to orphaned masters only if there are still at least a
# given number of other working slaves for their old master. This number
# is the "migration barrier". A migration barrier of 1 means that a slave
# will migrate only if there is at least 1 other working slave for its master
# and so forth. It usually reflects the number of slaves you want for every
# master in your cluster.
#
# Default is 1 (slaves migrate only if their masters remain with at least
# one slave). 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

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

# Hashes are encoded using a memory efficient data structure when they have a
# small number of entries, and the biggest entry does not exceed a given
# threshold. These thresholds can be configured using the following directives.
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

# Active rehashing uses 1 millisecond every 100 milliseconds of CPU time in
# order to help rehashing the main Redis hash table (the one mapping top-level
# keys to values). The hash table implementation Redis uses (see dict.c)
# performs a lazy rehashing: the more operation you run into a hash table
# that is rehashing, the more rehashing "steps" are performed, so if the
# server is idle the rehashing is never complete and some more memory is used
# by the hash table.
#
# The default is to use this millisecond 10 times every second in order to
# actively rehash the main dictionaries, freeing memory when possible.
#
# If unsure:
# use "activerehashing no" if you have hard latency requirements and it is
# not a good thing in your environment that Redis can reply from time to time
# to queries with 2 milliseconds delay.
#
# use "activerehashing yes" if you don't have such hard requirements but
# want to free memory asap when possible.
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
# slave  -> slave 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 slave clients, since
# subscribers and slaves 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 slave 256mb 64mb 60
client-output-buffer-limit pubsub 32mb 8mb 60

# 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

# 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

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

# Maximal effort for defrag in CPU percentage
# active-defrag-cycle-max 75
View Code

当修改配置文件后需要重新load一下配置文件,不然会报错:连接请求被拒,举例如下

[root@iZbp1hwh629hd4xz80i1z0Z bin]# redis-cli -p 6379
Could not connect to Redis at 127.0.0.1:6379: Connection refused
Could not connect to Redis at 127.0.0.1:6379: Connection refused
not connected> 
not connected> 
[root@iZbp1hwh629hd4xz80i1z0Z bin]# redis-server /etc/redis/6379.conf
4769:C 16 Dec 16:18:24.321 # oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo
4769:C 16 Dec 16:18:24.321 # Redis version=4.0.6, bits=64, commit=00000000, modified=0, pid=4769, just started
4769:C 16 Dec 16:18:24.321 # Configuration loaded
[root@iZbp1hwh629hd4xz80i1z0Z bin]# redis-cli -p 6379

着重说一下security的参数:

127.0.0.1:6379> ping
PONG
127.0.0.1:6379> config get requirepass # 获取redis的密码
1) "requirepass"
2) ""
127.0.0.1:6379> config set requirepass "123456" # 设置redis的密码
OK
127.0.0.1:6379> config get requirepass # 发现所有的命令都没有权限了
(error) NOAUTH Authentication required.
127.0.0.1:6379> ping
(error) NOAUTH Authentication required.
127.0.0.1:6379> auth 123456 # 使用密码进行登录!
OK
127.0.0.1:6379> config get requirepass
1) "requirepass"
2) "123456"

注意,设置密码后每次登录redis后想要操作必须要输入auth yourpassword 才行;

持久化RDB操作

  RDB:redis datebase,因为redis是内存数据库,不进行持久化的数据会断电丢失

 

  在指定的时间间隔内将内存中的数据集快照写入磁盘,也就是行话讲的Snapshot快照,它恢复时是将快照文件直接读到内存里。

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

有时候在生产环境我们会将这个文件进行备份!

rdb保存的文件是dump.rdb 都是在我们的配置文件中快照中进行配置的!

触发机制

1、save的规则满足的情况下,会自动触发rdb规则
2、执行 flushall 命令,也会触发我们的rdb规则!
3、退出redis,也会产生 rdb 文件
备份就自动生成一个 dump.rdb

 前面提到过,rdb条件在配置文件中有相关配置,示例如下:

save 30 3
# 如果30s内,如果至少进行了3次 key修改,就进行持久化操作,生成rdb文件

 删除rdb文件:

rm -rf dump.rdb  #删除rdb文件

恢复rdb文件

只需要将rdb文件放在我们redis启动目录就可以,redis启动的时候会自动检查dump.rdb 恢复其中的数据!

优点:

1、适合大规模的数据恢复!
2、对数据的完整性要求不高!
缺点:

1、需要一定的时间间隔进程操作!如果redis因意外宕机了,这个最后一次修改数据就没有的了!
2、创建进程的时候,会占用一定的内容空间!!

 AOF——Append Only File

   简单来说就是以日志的形式将我们的所有命令都记录下来(记录写操作,不记录读操作),恢复的时候就把这个文件全部在执行一遍

   默认是在关闭的,可以配置文件中修改

appendonly no

# The name of the append only file (default: "appendonly.aof")

appendfilename "appendonly.aof"

   一般的,rdb持久化就可以满足保存数据的需求,不需要用到aof

 

redis发布订阅(公众号订阅,微博关注等)

  Redis 发布订阅(pub/sub)是一种消息通信模式:发送者(pub)发送消息,订阅者(sub)接收消息。

假设频道 channel1 , 以及订阅这个频道的三个客户端 —— client1,2

序号命令及描述
1 PSUBSCRIBE pattern [pattern ...]
订阅一个或多个符合给定模式的频道。
2 PUBSUB subcommand [argument [argument ...]]
查看订阅与发布系统状态。
3 PUBLISH channel message
将信息发送到指定的频道。
4 PUNSUBSCRIBE [pattern [pattern ...]]
退订所有给定模式的频道。
5 SUBSCRIBE channel [channel ...]
订阅给定的一个或多个频道的信息。
6 UNSUBSCRIBE [channel [channel ...]]
指退订给定的频道。


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

窗口1,2均为订阅端,订阅频道1: channel1,用窗口3作为发送端:代码如下

窗口1:
127.0.0.1:6379> subscribe channel1 
Reading messages... (press Ctrl-C to quit)
1) "subscribe"
2) "channel1"
3) (integer) 1

窗口2:
127.0.0.1:6379> subscribe channel1 
Reading messages... (press Ctrl-C to quit)
1) "subscribe"
2) "channel1"
3) (integer) 1

窗口3:
127.0.0.1:6379> publish channel1 welcome!
(integer) 2
127.0.0.1:6379> 

窗口3的发送端 发送后的1,2均收到消息
127.0.0.1:6379> subscribe channel1 
Reading messages... (press Ctrl-C to quit)
1) "subscribe"
2) "channel1"
3) (integer) 1
1) "message"
2) "channel1"
3) "welcome!"

PS:redis订阅的缺点是:

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

redis 主从复制

  主从复制,是指将一台Redis服务器的数据,复制到其他的Redis服务器。前者称为主节点(Master/Leader),后者称为从节点(Slave/Follower), 数据的复制是单向的!只能由主节点复制到从节点(主节点以写为主、从节点以读为主)。

默认情况下,每台Redis服务器都是主节点,一个主节点可以有0个或者多个从节点,但每个从节点只能由一个主节点。

  作用:
    数据冗余:主从复制实现了数据的热备份,是持久化之外的一种数据冗余的方式。
    故障恢复:当主节点故障时,从节点可以暂时替代主节点提供服务(实现紧急故障恢复),是一种服务冗余的方式
    负载均衡:在主从复制的基础上,配合读写分离,由主节点进行写操作,从节点进行读操作,分担服务器的负载;尤其是在多读少写的场景下,通过多个从节点      分担负载,提高并发量。
    高可用基石:主从复制还是哨兵和集群能够实施的基础。
  用集群的原因:
    单台服务器难以负载大量的请求
    单台服务器故障率高,系统崩坏概率大
    单台服务器内存容量有限。

  主从图对应如下:(master主:以写为主,slave从:以读为主)

环境配置
  需要模拟多个服务,所以我们需要配置多个文件:

#先查看redis 当前库的基础信息
127.0.0.1:6379> info replication
# Replication
role:master
connected_slaves:0 #可以看到没有从机
master_replid:6e310ed1cfa7504bc8d16ee2fba0b6f1456fabf3
master_replid2:0000000000000000000000000000000000000000
master_repl_offset:0
second_repl_offset:-1
repl_backlog_active:0
repl_backlog_size:1048576
repl_backlog_first_byte_offset:0
repl_backlog_histlen:0
127.0.0.1:6379> 

由于担心我可怜的学生机服务器能不能撑住,所以测试从机数量设为2:

操作流程大致如下:

[root@iZbp1hwh629hd4xz80i1z0Z etc]# vim redis79.conf
[root@iZbp1hwh629hd4xz80i1z0Z etc]# vim redis80.conf
[root@iZbp1hwh629hd4xz80i1z0Z etc]# vim redis81.conf
[root@iZbp1hwh629hd4xz80i1z0Z etc]# redis-server redis79.conf
[root@iZbp1hwh629hd4xz80i1z0Z ~]# ps -ef|grep redis
root      2676     1  0 13:32 ?        00:00:00 redis-server 127.0.0.1:6381
root      5569  4001  0 13:33 pts/7    00:00:00 grep --color=auto redis
root     25964     1  0 13:30 ?        00:00:00 redis-server 127.0.0.1:6379
root     28305     1  0 13:31 ?        00:00:00 redis-server 127.0.0.1:6380

默认情况下,每台Redis服务器都是主节点,如下:

[root@iZbp1hwh629hd4xz80i1z0Z etc]# redis-cli -p 6379
127.0.0.1:6379> auth 123456
(error) ERR Client sent AUTH, but no password is set
127.0.0.1:6379> info replication
# Replication
role:master
connected_slaves:0
master_replid:707c5916fa326b0e87834068cf4327db20f1a79d
master_replid2:0000000000000000000000000000000000000000
master_repl_offset:0
second_repl_offset:-1
repl_backlog_active:0
repl_backlog_size:1048576
repl_backlog_first_byte_offset:0
repl_backlog_histlen:0
127.0.0.1:6379> 

现在分配从机就好:

可以理解为从机“认主”,配置80,81为从机,79位主机:

现在在窗口2运行客户端6380:

[root@iZbp1hwh629hd4xz80i1z0Z etc]# redis-cli -p 6380
127.0.0.1:6380> slaveof 127.0.0.1 6379
OK
127.0.0.1:6380> info replication
# Replication
role:slave
master_host:127.0.0.1
master_port:6379
master_link_status:up
master_last_io_seconds_ago:1
master_sync_in_progress:0
slave_repl_offset:14
slave_priority:100
slave_read_only:1
connected_slaves:0
master_replid:be7144093698e5f64b2b5ebf34ebf6f9af4be9e3
master_replid2:0000000000000000000000000000000000000000
master_repl_offset:14
second_repl_offset:-1
repl_backlog_active:1
repl_backlog_size:1048576
repl_backlog_first_byte_offset:1
repl_backlog_histlen:14
127.0.0.1:6380> 

发现本机已变成从机,同理,配置窗口3:从机6381,配置好后观察主机配置:

127.0.0.1:6379> info replication
# Replication
role:master
connected_slaves:2
slave0:ip=127.0.0.1,port=6380,state=online,offset=266,lag=0
slave1:ip=127.0.0.1,port=6381,state=online,offset=266,lag=0
master_replid:be7144093698e5f64b2b5ebf34ebf6f9af4be9e3
master_replid2:0000000000000000000000000000000000000000
master_repl_offset:266
second_repl_offset:-1
repl_backlog_active:1
repl_backlog_size:1048576
repl_backlog_first_byte_offset:1
repl_backlog_histlen:266
127.0.0.1:6379> 

已经拥有两台从机了!

当然,实际应当用配置文件中的replicaof  ip port 来配置主从关系~

验证主机写,从机读

127.0.0.1:6380> keys * #从机读取主机的key
1) "k1"
127.0.0.1:6380> set k2 v2
(error) READONLY You can't write against a read only slave.
127.0.0.1:6380> 

验证主机宕机,从机情况:

step1:shutdown 主机服务,查看当前进程:

 step2:配置从机81为主机:

127.0.0.1:6381> slaveof no one
OK
127.0.0.1:6381> info replication
# Replication
role:master
connected_slaves:0
master_replid:db65d6dce86c29cd2d54ec8d5621e6aed0bf1ac5
master_replid2:be7144093698e5f64b2b5ebf34ebf6f9af4be9e3
master_repl_offset:976
second_repl_offset:977
repl_backlog_active:1
repl_backlog_size:1048576
repl_backlog_first_byte_offset:253
repl_backlog_histlen:724
127.0.0.1:6381> 

不过如果主机宕机恢复,从机不重新认主的话依然是光杆司令的

哨兵模式:监控主机是否故障,指认从机变为主机来扛大梁:(有单哨兵和多哨兵模式)

多哨兵模式:

 相比较上面主从复制方法:当主服务器宕机后,需要手动把一台从服务器切换为主服务器,这就需要人工干预,费事费力,还会造成一段时间内服务不可用。这不是一种推荐的方式,更多时候,我们优先考虑哨兵模式。

哨兵模式是一种特殊的模式,首先Redis提供了哨兵的命令,哨兵是一个独立的进程,作为进程,它会独立运行。其原理是哨兵通过发送命令,等待Redis服务器响应,从而监控运行的多个Redis实例。

由于云服务器配置问题,目前用单哨兵来学习哨兵模式:

 配置哨兵:

sentinel monitor mymaster 127.0.0.1 6379
#数字1表示 :当一个哨兵主观认为主机断开,就可以客观认为主机故障,然后开始选举新的主机。

启动哨兵:

[root@iZbp1hwh629hd4xz80i1z0Z ~]# redis-sentinel sentinel.conf
14609:X 21 Dec 14:20:33.065 # oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo
14609:X 21 Dec 14:20:33.065 # Redis version=4.0.6, bits=64, commit=00000000, modified=0, pid=14609, just started
14609:X 21 Dec 14:20:33.065 # Configuration loaded
                _._                                                  
           _.-``__ ''-._                                             
      _.-``    `.  `_.  ''-._           Redis 4.0.6 (00000000/0) 64 bit
  .-`` .-```.  ```\/    _.,_ ''-._                                   
 (    '      ,       .-`  | `,    )     Running in sentinel mode
 |`-._`-...-` __...-.``-._|'` _.-'|     Port: 26379
 |    `-._   `._    /     _.-'    |     PID: 14609
  `-._    `-._  `-./  _.-'    _.-'                                   
 |`-._`-._    `-.__.-'    _.-'_.-'|                                  
 |    `-._`-._        _.-'_.-'    |           http://redis.io        
  `-._    `-._`-.__.-'_.-'    _.-'                                   
 |`-._`-._    `-.__.-'    _.-'_.-'|                                  
 |    `-._`-._        _.-'_.-'    |                                  
  `-._    `-._`-.__.-'_.-'    _.-'                                   
      `-._    `-.__.-'    _.-'                                       
          `-._        _.-'                                           
              `-.__.-'                                               

14609:X 21 Dec 14:20:33.151 # WARNING: The TCP backlog setting of 511 cannot be enforced because /proc/sys/net/core/somaxconn is set to the lower value of 128.
14609:X 21 Dec 14:20:33.182 # Sentinel ID is 1a581b8ad032d3131033abad3fc8e89e81e42c67
14609:X 21 Dec 14:20:33.182 # +monitor master myredis 127.0.0.1 6379 quorum 1  #监控主机ipxx和 6379,主观票数为1


可以看到其端口号默认为26379,#监控主机ipxx和 6379,主观票数为1

 我们中断79主机后,发现哨兵打印信息出现变化:

17526:X 21 Dec 14:26:47.444 # +monitor master myredis 127.0.0.1 6379 quorum 1
17526:X 21 Dec 14:26:47.475 * +slave slave 127.0.0.1:6380 127.0.0.1 6380 @ myredis 127.0.0.1 6379
17526:X 21 Dec 14:26:47.524 * +slave slave 127.0.0.1:6381 127.0.0.1 6381 @ myredis 127.0.0.1 6379
17526:X 21 Dec 14:27:25.515 # +sdown master myredis 127.0.0.1 6379
17526:X 21 Dec 14:27:25.515 # +odown master myredis 127.0.0.1 6379 #quorum 1/1
17526:X 21 Dec 14:27:25.515 # +new-epoch 2
17526:X 21 Dec 14:27:25.515 # +try-failover master myredis 127.0.0.1 6379
17526:X 21 Dec 14:27:25.543 # +vote-for-leader 1a581b8ad032d3131033abad3fc8e89e81e42c67 2
17526:X 21 Dec 14:27:25.543 # +elected-leader master myredis 127.0.0.1 6379
17526:X 21 Dec 14:27:25.543 # +failover-state-select-slave master myredis 127.0.0.1 6379
17526:X 21 Dec 14:27:25.617 # +selected-slave slave 127.0.0.1:6381 127.0.0.1 6381 @ myredis 127.0.0.1 6379
17526:X 21 Dec 14:27:25.617 * +failover-state-send-slaveof-noone slave 127.0.0.1:6381 127.0.0.1 6381 @ myredis 127.0.0.1 6379
17526:X 21 Dec 14:27:25.709 * +failover-state-wait-promotion slave 127.0.0.1:6381 127.0.0.1 6381 @ myredis 127.0.0.1 6379
17526:X 21 Dec 14:27:25.942 # +promoted-slave slave 127.0.0.1:6381 127.0.0.1 6381 @ myredis 127.0.0.1 6379
17526:X 21 Dec 14:27:25.942 # +failover-state-reconf-slaves master myredis 127.0.0.1 6379
17526:X 21 Dec 14:27:25.994 * +slave-reconf-sent slave 127.0.0.1:6380 127.0.0.1 6380 @ myredis 127.0.0.1 6379
17526:X 21 Dec 14:27:27.051 * +slave-reconf-inprog slave 127.0.0.1:6380 127.0.0.1 6380 @ myredis 127.0.0.1 6379
17526:X 21 Dec 14:27:27.051 * +slave-reconf-done slave 127.0.0.1:6380 127.0.0.1 6380 @ myredis 127.0.0.1 6379
17526:X 21 Dec 14:27:27.103 # +failover-end master myredis 127.0.0.1 6379
17526:X 21 Dec 14:27:27.103 # +switch-master myredis 127.0.0.1 6379 127.0.0.1 6381
17526:X 21 Dec 14:27:27.103 * +slave slave 127.0.0.1:6380 127.0.0.1 6380 @ myredis 127.0.0.1 6381
17526:X 21 Dec 14:27:27.103 * +slave slave 127.0.0.1:6379 127.0.0.1 6379 @ myredis 127.0.0.1 6381
17526:X 21 Dec 14:27:57.178 # +sdown slave 127.0.0.1:6379 127.0.0.1 6379 @ myredis 127.0.0.1 6381

我们看到了:switch-master myredis 127.0.0.1 6379 127.0.0.1 6381这一句,可以猜测6381被选为了新的主机,事实上确实如此:

127.0.0.1:6381> info replication
# Replication
role:master
connected_slaves:1
slave0:ip=127.0.0.1,port=6380,state=online,offset=10038,lag=1
master_replid:5949eecb506754b4e2fa6491837b82233bfb1921
master_replid2:f37ab726110e0d6dde051c109d7ac603c1a3917b
master_repl_offset:10038
second_repl_offset:462
repl_backlog_active:1
repl_backlog_size:1048576
repl_backlog_first_byte_offset:1
repl_backlog_histlen:10038

如果这个时候我们把主机79重新启动,会发现哨兵输出如下:

17526:X 21 Dec 14:32:41.861 * +convert-to-slave slave 127.0.0.1:6379 127.0.0.1 6379 @ myredis 127.0.0.1 6381

6379被降为81的从机了,这点其实和主从复制类似,区别只是主从中,主机重连后不会被自动分配为从机。

  

原文地址:https://www.cnblogs.com/dabuliu/p/15712726.html