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

redis 6.0 Source code :

Database in server

Redis The server keeps most of the information in server.h/redisServer.redis The data is stored in redisServer Medium redisDb In structure .

struct redisServer {
// ...
redisDb *db; // Database list
// ...
int dbnum; // Number of databases
// ...
  • db Each of them redisDb Structure represents a database .
  • When initializing the server , The program will depend on the state of the server dbnum Property to determine how many databases should be created .
  • dbnum The value of the property is configured by the server database The choice decides , By default , The value of this option is 16, therefore Redis By default, the server creates 16 A database .

Database key space

Redis Is a key value to the database server , Each database in the server consists of a server.h/redisDb Structural representation .

among ,redisDb Of dict The dictionary property holds all key value pairs in the database , We call this dictionary key space (key space):

typedef struct redisDb {
dict *dict;
// ...
} redisDb;

dict The data in is one-to-one corresponding to the key value pairs we usually operate :

  • dict Of key It's in the database key, String type
  • dict Of value It's in the database value , This value could be zero stringhashzsetsetlist Any one of them


If we're in the database , Execute the following command :

redis > SET str_key str_value
redis > RPUSH list_key a b c
(integer) 3

Two new ones key The structure of is shown in the figure below :

It's clear from the example above that Redis How data is organized , Adding, deleting, modifying and checking means to dict The operation of , I won't go into details here .

Key The expiration time of

1. data structure

redisDb Medium expires Property holds all of key The expiration time of , Let's call it Out of date Dictionary Well .

  • Keys in expired dictionaries , It's a pointer , Pointing to real data key, It won't waste space. Save it one more time
  • Values in expired dictionaries , What we save is the specific expiration time point , Timestamps accurate to milliseconds
typedef struct redisDb {
// ...
// Save all key The expiration time of
dict *expires;
// ...
} redisDb;

command TTLPTTL It's all about looking up the expiration date of this expired dictionary , Then subtract the current time , What you get is the time left .

2. Be overdue key Delete policy for

One key When the expiration time is up , How to delete it ?Redis Two strategies are used : Lazy deletion 、 Delete periodically

Lazy deletion

Lazy deletion strategy refers to :key After expiration , No immediate deletion of , It's reading and writing key When , That's right key To delete .

The code is implemented in db.c/expireIfNeeded In the method . all key Before reading and writing , Will call first expireIfNeeded Yes key Inspection , If expired , Delete .

Delete periodically

The periodic deletion policy refers to :Redis Every once in a while , Take a certain amount of from the database at random key Inspection , If expired , Then delete .

The code is implemented in expire.c/activeExpireCycle In the method .

Redis Design and implementation : More articles on the database

  1. 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 ...

  2. 《Redis Design and implementation 》- database

    1. Database structure in the server Redis The server keeps all databases in the server state redisServer Structural db Array , from redisDb Structure represents a database struct redisServer ...

  3. Redis Design and implementation —— The realization of stand-alone database

    database Database in server redisClient Switch database redis The default target database of the client is 0 The database , Can pass SELECT Command to switch the target database . Client status redisClient Structural db Properties record ...

  4. 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 ...

  5. 《Redis Design and implementation 》 Reading notes

    <Redis Design and implementation > Reading notes I love the process of writing this book , In an open source way , Trusteeship Git To create on : The author read through Redis Source code , And shared detailed annotated source code , Let's learn Redis My friend is a lot easier : reading ...

  6. reread redis Design and implementation

    Read it again redis Design and implementation , The harvest is good too , Put some doubts before :redis The principle of the jump table .redis Persistent methods .redis Copy .redis sentinel.redis Cluster etc. , I've been familiar with it all over again , ...

  7. 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 : Check all records : similar sql Of select from table_na ...

  8. Redis note (3) Multi database implementation

    1. Preface This chapter is an introduction. redis Three ways of multi service implementation , As simple and clear as possible to summarize . 2. Copy Replication can also be called master-slave mode . Let's say I have two redis service , In a, In a ...

  9. 《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 ...

  10. 【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 ...

Random recommendation

  1. A word about java Serialization problem , See how much you know ————

    Here's the question , I'll answer later Known classes are Test and Test2, Ask twice what the output of the main program is (SerializeUtil It's just a serialized utility class ) class Test public class Test imple ...

  2. ST The second assignment , Related program tests and test cases

    public static int findLast(int[]x,int y){ for(int i = x.length-1;i>0;i--){//i>=0 if(x[i] == y) ...

  3. python Through custom exception , Early exit method

    python Exit operation , After searching, it's all return.exit() etc. return: Exit a method , And returns a value exit(): sign out python   What you want to achieve : Method A Multiple methods are invoked in , Method B. Method C.. ...

  4. HighCharts Detailed configuration parameters and Query options table

    summary : As an excellent interactive chart making tool ,HighCharts There's a full range of options . Parameters and other configuration information . In order to help you master HighCharts, Today, we've organized HighCharts All configuration information and instructions for , Put it ...

  5. A powerful LogParser Of UI Tools --logparserlizard brief introduction

    Log analysis , especially IIS journal , Most people think of LogParser Tools , It's really strong . But the operation interface of command line makes many non professional managers fear , Ok now , There's a visual LogParser Of UI The tool is ready to use ! Log ...

  6. 【 turn 】Android Several ways of timer implementation and removeCallbacks The failure problem is explained in detail -- Pretty good

    Original website : There are many ways to implement timers , Here, I will briefly introduce several ways (1) Use Handler + ...

  7. Java Common danger signals in development ( On )

    This article comes from my in InfoQ Chinese station original article , The original address is : Dustin Ma ...

  8. Chapter 2 Open Book&mdash;&mdash;26

    "Oh." He let it drop. I looked away awkwardly. Oh , He let it go . I looked awkwardly away . " Oh ." He is no longer entangled in this problem . ...

  9. Golang Of interface practice

    This is the second implementation I haven't seen in any other language ,go Of interface It can be said that it is unique , Let's practice it carefully . interface What is the type ?interface A type defines a set of methods , If an object implements a connection ...

  10. XXS level5

    (1) Try the fourth level , I can't find out , View page source code , Find out on There's an underline in the middle (2) see PHP Source code <?php ini_set("display_errors", 0); $ ...