The analysis of this paper is based on Redis 6.0 Version source code

redis 6.0 Source code :https://github.com/redis/redis/tree/6.0

stay Redis in , There are five types of data , All of them are encapsulated into one data type :redisObject. The definition is as follows :

typedef struct redisObject {
unsigned type:4; // type
unsigned encoding:4; // code
unsigned lru:LRU_BITS; // Recently visited
int refcount; // Number of citations
void *ptr; // Pointer to specific underlying data
} robj;

One 、 type

typedef struct redisObject {
unsigned type:4; // type
} robj;

Types are the five common object types .

The new version of the constant name is OBJ Prefix , The old version is REDIS Prefix ( Such as REDIS_STRING )

Type constant Object name
OBJ_STRING String object
OBJ_LIST List objects
OBJ_SET A collection of objects
OBJ_ZSET An orderly collection of objects
OBJ_HASH Hash object

TYPE Command can output specified key The object type of the value of .

redis > set str_key str_value
OK
redis > TYPE
string
Object name TYPE Command output
String object string
List objects list
A collection of objects set
An orderly collection of objects zset
Hash object hash

Two 、 code

typedef struct redisObject {
unsigned encoding:4; // code
} robj;

Of the five types , There may be different codes for each type . The main purpose of coding is to make a balance between saving memory and improving performance .

  • When the amount of data is small , Will be used compact ( Low performance ) Data structure of
  • When the amount of data reaches a certain threshold , It's going to move from a compact structure to high efficiency Data structure of

Due to limited space , The coding is more complicated . So the coding will be written in the following article , Hey, hey, hey

3、 ... and 、 Recently visited

typedef struct redisObject {
unsigned lru:LRU_BITS; // Recently visited
} robj;

When Redis When memory usage reaches the specified threshold ,Redis Memory will be recycled , There are many strategies for recycling , Among them LRU Strategy .

LRU To put it simply , Recently modified or visited , It's right in front . When it comes to elimination , Just eliminate the elements behind . The eliminated elements are relatively long without visiting / Revised .

Redis Record this latest visit time , Just for LRU The strategy is .

command OBJECT IDLETIME You can see key Since the last visit .

Due to limited space , Let's put the specific elimination strategy in the following article , Hey, hey, hey .

Four 、 Number of citations

typedef struct redisObject {
int refcount; // Number of citations
} robj;

refcount The main role of the object is reference counting and memory recycling .refcount It changes with the state of use of the object :

  • When creating a new object , The value of the reference count is initialized to 1;
  • When an object is used by a new program , Its reference count will be increased by one ;
  • When an object is no longer used by a program , Its reference count is subtracted by one ;
  • When the reference count of an object changes to 0 when , The memory occupied by the object is released .

command OBJECT REFCOUNT You can view the specified key The quoted count of .

Shared objects

When will the object be used by the new program ?

To save memory ,Redis At initialization time , Create good 0 ~ 9999 The object of , follow-up 0 ~ 9999 These shared objects are used for all integer values of , Objects are not recreated .

server.h

#define OBJ_SHARED_INTEGERS 10000

object.c

// ...
if (value >= 0 && value < OBJ_SHARED_INTEGERS...)
// ...

5、 ... and 、 The pointer

typedef struct redisObject {
void *ptr; // Pointer to specific underlying data
} robj;

A pointer usually points to the underlying data .

With one exception , On duty string type , And the code is int when , This is the integer value that is saved , Instead of Pointers .

About the structure of the underlying data , I'll say later .

Redis Design and implementation :Redis More articles about objects

  1. How to use redis Design a relational database

    Catalog redis Design a relational database Preface Design user information table structure hash Storage record set Storage id Icon Indexes / Inquire about : 1.select Check all records : similar sql Of select from table_na ...

  2. Redis Design and implementation ( One ~ Five integrated versions )【 Carry 】

    Redis Design and implementation ( One ~ Five integrated versions ) by @ Passing calf One Preface The project uses redis, But it uses the most basic functions , For example, simple slave Mechanism , The data structure uses only strings . But I've been hearing that redis Is a very ...

  3. Redis Design and implementation - Internal data structure

    . : This book is 2015 year 11 I started reading in January , It took about a month to read through , Recently, due to the need to redis Do some in-depth understanding of , So it took more than two months to read it carefully , Because this book is designed with a lot of content , And the content of each part is more detailed ...

  4. Redis note (1) Data structures and objects

    1. Preface This series of blogs records redis Design and implement a Book of notes , Extract knowledge from books , Omit the relevant instructions , Convenient access . 2. Basic data structure 2.1 Simple dynamic string SDS(simple dynamic string) structure ...

  5. 《Redis Design and implementation 》

    <Redis Design and implementation > essential information author : Huang Jianhong The title of the series : Database technology series Press. : Mechanical industry press ISBN:9787111464747 Shelf time :2014-6-3 Publication date :2014 ...

  6. 180713-Spring With the help of Redis Design the extension of access counter

    I wrote a blog before , A brief introduction to how to use Redis coordination Spring Building a web Access counter for , The previous content is relatively elementary , Now consider extending it , New visitor record Record the total number of visitors to the current site ( according to Ip Or equipment number ) ...

  7. 【Redis】 Four 、Redis Design principles and related issues

    ( 6、 ... and )Redis Design principles and related issues    Through the above about Redis Five types of data . Related advanced features and the use of some simple examples , Yes Redis We should have a good command of the usage and main use of , But there are still some problems of principle. Let's make an exploration in this part ...

  8. Explore Redis Design and implementation 9: database redisDb Key expiration deletion policy

    This article is transferred from the Internet This series of articles will be sorted out by me in GitHub Upper <Java Interview guide > Warehouse , More wonderful contents can be found in my warehouse https://github.com/h2pl/Java-Tutorial ...

  9. Explore Redis Design and implementation 8: Data structures that connect the underlying layer and the surface robj

    This article is transferred from the Internet This series of articles will be sorted out by me in GitHub Upper <Java Interview guide > Warehouse , More wonderful contents can be found in my warehouse https://github.com/h2pl/Java-Tutorial ...

  10. Explore Redis Design and implementation 4:Redis Internal data structure details ——ziplist

    This article is transferred from the Internet This series of articles will be sorted out by me in GitHub Upper <Java Interview guide > Warehouse , More wonderful contents can be found in my warehouse https://github.com/h2pl/Java-Tutorial ...

Random recommendation

  1. [8.3] Magic Index

    A magic index in an array A[0...n-1] is defined to be an index such that A[i] = i. Given a sorted ar ...

  2. Incisive jquery Learning notes

    1.$("#tt") What you get is always a jquery object , Therefore, it is necessary to judge whether there is an object on the page, which cannot be like js in if($("#tt")){ } But through : ){ } ps ...

  3. java No sign shift (&gt;&gt;&gt;) And signed shift (&gt;&gt;)

    java in >>(<<) Represents a signed shift .<<<(>>>) Represents an unsigned shift Such as : int num = 22; Binary is 0001 0110, nu ...

  4. mysql Database connection pool Write by hand

    The source code comes from http://www.toutiao.com/a6350448676050174209/, Keep it for future reference Let's start with the project top chart Then list the source code of each file : MyPool.java( Namely ...

  5. Linux The following access to the physical address

    Reference link :http://zhuhaibobb.blog.163.com/blog/static/2744006720101049030606/ Linux The kernel provides /dev/mem drive , Provides a direct ...

  6. IOS Advanced development runtime( Two )

    Two . The soul moving method Use runtime You can also swap two functions . Paste the code and execution results first . #import <Foundation/Foundation.h> @interface DZLPerson : ...

  7. obtain SQL The execution time of the segment

    Yes SQL To optimize You often need to know this SQL Statement execution time , Here is a common practice of mine DECLARE @d DATETIME SET @d=GETDATE() --do something --for ...

  8. easyui-combobox binding json data

    With C# Language Get data in the background , No more nonsense , Let's look at serialization first json data /// <summary> /// Object turn JSON /// </summary> /// <param ...

  9. ICE BOX To configure , Use ---- Chapter one

    One Theoretical part (1)  Why use icebox? icebox server Instead of the usual server. icebox It's for the convenience of centralized management of multiple ice Built on service . It uses icebox The server , hold ice clothing ...

  10. understand Java Class loading mechanism ( translation )

    understand java Class loading mechanism You want to write class loaders ? Or you meet ClassCastException abnormal , Or you come across a strange LinkageError State constraint exception . We should take a closer look at java Class loading handles . What is class loading ...