Redis核心对象
reids中定义了一个数据结构用来统一表示各种数据类型,它叫做redisObject
typedef struct redisObject {
unsigned type:4; //记录数据值的类型:string、list、hash、set、zset
unsigned encoding:4; //记录数据值的编码格式
unsigned lru:LRU_BITS; //记录操作时间,当redis内存超限时,该值可辅助lru算法清理数据
int refcount; //记录当前对象被引用的次数
void *ptr; //记录存储数据位置的指针
} robj;
Redis数据类型
截止到redis6版本,一共定义了以下七种基本数据类型
#define OBJ_STRING 0 /* String object. */
#define OBJ_LIST 1 /* List object. */
#define OBJ_SET 2 /* Set object. */
#define OBJ_ZSET 3 /* Sorted set object. */
#define OBJ_HASH 4 /* Hash object. */
#define OBJ_MODULE 5 /* Module object. */ 下面这两个数据类型是之前没有的
#define OBJ_STREAM 6 /* Stream object. */
可通过命令type key来查看数据值的所属类型
SDS
要了解redis字符串的编码格式,首先来了解以下SDS
redis使用SDS(“简单动态字符串”)结构体来存储字符串,redis源码中定义了如下几种结构体,根据字符串长度使用不同结构体来存储,尽可能对底层进行优化
/* Note: sdshdr5 is never used, we just access the flags byte directly.
* However is here to document the layout of type 5 SDS strings. */
struct __attribute__ ((__packed__)) sdshdr5 {
unsigned char flags; /* 3 lsb of type, and 5 msb of string length */
char buf[];
};
struct __attribute__ ((__packed__)) sdshdr8 {
uint8_t len; /* used */ //字符串长度
uint8_t alloc; /* excluding the header and null terminator */ //分配内存的大小