Introduction to Redis Object Types
Redis is a key-value database where each key and value is represented as an object. For example, when you run the following command:
[plain]
Redis> SET message "hello redis"
The key "message" is an object that contains the string "message", and the value is another object containing the string "hello redis".
Redis supports five main object types, which are:
- REDIS_STRING (string object)
- REDIS_LIST (list object)
- REDIS_HASH (hash object)
- REDIS_SET (set object)
- REDIS_ZSET (sorted set object)
Each Redis object has a specific structure defined in C, as shown below:
[cpp]
/*
* Redis object
*/
typedef struct redisObject {
// Type of the object
unsigned type:4;
// Unused (alignment bit)
unsigned notused:2;
// Encoding used for the object
unsigned encoding:4;
// LRU time (relative to server.lruclock)
unsigned lru:22;
// Reference count
int refcount;
// Pointer to the actual value
void *ptr;
} robj;
The 'type' field indicates the object's type, such as string, list, or hash. However, the internal data structure used to implement each type can vary depending on efficiency and performance considerations. This is where the 'encoding' field comes into play.
Redis Object Underlying Data Structures
Redis uses several underlying data structures to represent objects. These include:
- REDIS_ENCODING_INT: A long integer
- REDIS_ENCODING_EMBSTR: A simple dynamic string encoded with embstr
- REDIS_ENCODING_RAW: A standard dynamic string
- REDIS_ENCODING_HT: A dictionary (hash table)
- REDIS_ENCODING_LINKEDLIST: A double-ended linked list
- REDIS_ENCODING_ZIPLIST: A compressed list
- REDIS_ENCODING_INTSET: An integer set
- REDIS_ENCODING_SKIPLIST: A skip list combined with a dictionary
For string objects, the encoding can be either int, raw, or embstr. If the string content can be converted to a long, it will be stored as an integer, and the ptr will point to that long value. Otherwise, it will use either embstr or raw encoding.
Embstr was introduced in Redis 3.0 and is optimized for small strings. If the length of the string is less than or equal to 39 bytes, Redis uses embstr; otherwise, it defaults to raw. This is implemented in the code as follows:
[cpp]
#define REDIS_ENCODING_EMBSTR_SIZE_LIMIT 39
robj *createStringObject(char *ptr, size_t len) {
if (len <= REDIS_ENCODING_EMBSTR_SIZE_LIMIT)
return createEmbeddedStringObject(ptr, len);
else
return createRawStringObject(ptr, len);
}
YIWU JUHE TRADING COMPANY , https://www.nx-vapes.com