redis如何分配哈希槽

Redis 集群中内置了 16384 个哈希槽,当需要在 Redis 集群中放置一个 key-value

时,redis 先对 key 使用 crc16 算法算出一个结果,然后把结果对 16384 取模,

这样每个 key 都会对应一个编号在 0-16383 之间的哈希槽,redis 会根据节点数量大

致均等的将哈希槽映射到不同的节点。


crc 16 算法

unsigned int keyHashSlot(char *key, int keylen) {  #
    int s, e; /* start-end indexes of { and } */

    for (s = 0; s < keylen; s++)
        if (key[s] == '{') break;

    /* No '{' ? Hash the whole key. This is the base case. */
    if (s == keylen) return crc16(key,keylen) & 0x3FFF;

    /* '{' found? Check if we have the corresponding '}'. */
    for (e = s+1; e < keylen; e++)
        if (key[e] == '}') break;

    /* No '}' or nothing betweeen {} ? Hash the whole key. */
    if (e == keylen || e == s+1) return crc16(key,keylen) & 0x3FFF;

    /* If we are here there is both a { and a } on its right. Hash
     * what is in the middle between { and }. */
    return crc16(key+s+1,e-s-1) & 0x3FFF;
}


你可能感兴趣的:(大数据平台)