拼多多面试:为什么RedisCluster有16384个槽?

面试官

:你知道为什么RedisCluster有 16384
个slot么?



:应该是作者脑袋一热随意定的一个数值吧?(心里嘀咕:如果 antirez
当时定的是8192,你又该怎么问呢?)

面试官
:。。。,今天的面试就到这里,你回去等消息吧


:。。。

引言

现在redis集群架构,redis cluster用的会比较多。架构图如下图所示:


对于客户端请求的key,根据公式 HASH_SLOT=CRC16(key) mod 16384
,计算出映射到哪个分片上,然后Redis会去相应的节点进行操作!

那大家思考过,为什么有16384个槽么?

ps
: CRC16
算法产生的hash值有16bit,该算法可以产生2^16-=65536个值。换句话说,值是分布在0~65535之间。那作者在做 mod
运算的时候,为什么不 mod
65536,而选择 mod
16384?
其实我当初第一次思考这个问题的时候,我心里是这么想的,作者应该是觉得16384就够了,然后我就开始查这方面资料。

很幸运的是,这个问题,作者是给出了回答的!
地址如下:

https://github.com/antirez/redis/issues/2576

作者原版回答如下:
The reason is:

  • Normal heartbeat packets carry the full configuration of a node, that can be replaced in an idempotent way with the old in order to update an old config. This means they contain the slots configuration for a node, in raw form, that uses 2k of space with16k slots, but would use a prohibitive 8k of space using 65k slots.
  • At the same time it is unlikely that Redis Cluster would scale to more than 1000 mater nodes because of other design tradeoffs.

So 16k was in the right range to ensure enough slots per master with a max of 1000 maters, but a small enough number to propagate the slot configuration as a raw bitmap easily. Note that in small clusters the bitmap would be hard to compress because when N is small the bitmap would have slots/N bits set that is a large percentage of bits set.
因此,能看懂上面那段话的读者。这篇文章不用看了,因为作者讲的很清楚了。本文只是对上面那段话做一些解释而已。

正文

基础

我们回忆一下 Redis Cluster
的工作原理!
这里要先将节点握手讲清楚。我们让两个redis节点之间进行通信的时候,需要在客户端执行下面一个命令

127.0.0.1:7000>cluster meet 127.0.0.1:7001

如下图所示


意思很简单,让7000节点和7001节点知道彼此存在!
在握手成功后,两个节点之间会 定期
发送ping/pong消息,交换 数据信息
,如下图所示。