Redis中String的底层实现

查看Key的内部编码

object encoding key

String的三种编码

  1. int
  2. embstr
  3. raw

int

存储长整型,且长度不能超过2^64-1

emstr

存储字符串。内存是连续的,有长度限制(39/44个字节,不同版本有差异),且是只读。

raw

存储字符串。内存是非连续的,长度超出限制时使用。需要注意的是,如果使用append追加key的value,不论其是否int或者embstr的长度是否超出限制,编码会变成raw。

String经典应用场景

  1. 缓存
  2. 用户会话
  3. 计数器(increment decrement)

参考:
object.c 中,长度限制(版本:3.2)

/* Create a string object with EMBSTR encoding if it is smaller than
 * REIDS_ENCODING_EMBSTR_SIZE_LIMIT, otherwise the RAW encoding is
 * used.
 *
 * The current limit of 39 is chosen so that the biggest string object
 * we allocate as EMBSTR will still fit into the 64 byte arena of jemalloc. */
#define OBJ_ENCODING_EMBSTR_SIZE_LIMIT 44
robj *createStringObject(const char *ptr, size_t len) {
    if (len <= OBJ_ENCODING_EMBSTR_SIZE_LIMIT)
        return createEmbeddedStringObject(ptr,len);
    else
        return createRawStringObject(ptr,len);
}



Redis内部存储原理大纲

原文地址:https://www.cnblogs.com/wugang/p/14233043.html