search
HomeDatabaseRedisWhat is the principle of Redis data structure?

    RedisDb

    The Redis server has 16 databases by default, and one database corresponds to one RedisDB data structure.

    typedef struct redisDb {
        dict *dict;
        dict *expires;
        dict * blocking_keys;
        dict * ready_keys;
        dict * watched_keys;
        ......
    }
    • dict: key space hash table, used to store all key-value pairs

    • expires: expiration time hash table, used to store the expiration of keys Time

    • blocking_keys: keys in blocked state and corresponding client

    • ready_keys: keys in unblocked state and corresponding client, and blocking_keys The attributes are relative

    • watched_keys: watch key and corresponding client, mainly used for transactions

    RedisObject

    Redis key The values ​​are all redisObject objects. Every time we create a new key-value pair in the Redis database, a redisObject object for the key name and a redisObject object for the key value will be generated

    trpedef struct RedisObject {
        int4 type;
        int4 encoding;
        void *ptr;
        int24 lru;
        int32 refcount;
    }
    Field Description Explanation
    type is used to represent the type corresponding to Redis String, list, hash, set, zset, stream, etc. are represented by enumerations
    encoding Internal encoding int , embstr, raw, hashtable, quicklist, ziplist, intset, skiplist, etc., represented by enumeration
    lru 24 bits, optional LFU or LRU When it is LRU, it represents the last access time; when it is LFU, the high 16 bits are used to represent the access time at the minute level, and the low 8 bits are used to represent the access frequency. The increase in frequency uses a probability algorithm, the base The larger it is, the harder it is to increase; when the access time is updated, there is a certain probability that the access frequency will be attenuated. (Common to both) Access time is a modulo of a number, and the current time is also modulo. If the current time is greater than the access time, it is the difference between the two numbers; if the current time is less than the access time, it is the current time plus the modulus and the access time. The difference
    refcount Reference count The initial value is 1, which is of little reference significance in practical applications
    ptr Pointer, occupies 8 bytes, points to the address of the data dict, expires, etc., the pointer points to the same address

    object command is the related operation on RedisObject.

    Modify the memory elimination strategy

    object idletime key # Returns the idle time of the key, that is, the approximate description of the time since the last time the key was read and written. It is not available in lfu mode

    config set maxmemory-policy volatile-lfu # 修改内存淘汰策略
    set name zhangsan
    object freq name # 获取计数值,仅lfu模式下可用,初始化为5
    
    get name
    
    object freq name # 再次访问,返回为6

    int

    When the string value is an integer and is less than or equal to the maximum value of long, the encoding is int type, and ptr directly points to the int type address

    embstr and raw

    Redis The string is called SDS (Simple Dynamic String, simple string), corresponding to the key, non-integer String value

    trpedef struct SDS {
        int8 capacity; // 数组容量
        int8 len; // 实际长度
        int8 flags;
        byte[] content; // 数组内容
    }

    It can be seen that SDS is similar to Java's ArrayList structure, and it is also Allocate an initial length and expand it when the length exceeds. Redis stipulates that the length of the string cannot exceed 512M.

    When the length is particularly short, use embstr form to store; when the length exceeds 44 bytes, use raw form to store.

    It is known that the maximum allocation unit of the memory allocator is 64 bytes, RedisObject occupies 16 bytes, the SDS identifier occupies 3 bytes, and a string ending with NULL requires one byte, so when the string length When it is less than or equal to 44, memory only needs to be allocated once. RedisObject and SDS are in the same memory unit. We call this data structure embstr, while those that are not in the same memory unit are called raw.

    dict

    dict (encoding is hashtable type, dictionary) corresponds to hash, set, zset (used to store the mapping between value and score) collection.

    dict is similar to Java's HashMap structure. The difference is that HashMap expansion requires an array, then traverses it, re-hashes the old data and hangs it under the array. As a single-threaded Redis, it is difficult To withstand such a time-consuming process, it uses two arrays, returns first, and then moves the data bit by bit when it is free. After the move is completed, the old data is cleared. We call this process progressive rehash .

    typedef struct dict {
        dictht ht[2];
    }

    The above is the detailed content of What is the principle of Redis data structure?. For more information, please follow other related articles on the PHP Chinese website!

    Statement
    This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
    Redis: Caching, Session Management, and MoreRedis: Caching, Session Management, and MoreMay 01, 2025 am 12:03 AM

    Redis's functions mainly include cache, session management and other functions: 1) The cache function stores data through memory to improve reading speed, and is suitable for high-frequency access scenarios such as e-commerce websites; 2) The session management function shares session data in a distributed system and automatically cleans it through an expiration time mechanism; 3) Other functions such as publish-subscribe mode, distributed locks and counters, suitable for real-time message push and multi-threaded systems and other scenarios.

    Redis: Exploring Its Core Functionality and BenefitsRedis: Exploring Its Core Functionality and BenefitsApr 30, 2025 am 12:22 AM

    Redis's core functions include memory storage and persistence mechanisms. 1) Memory storage provides extremely fast read and write speeds, suitable for high-performance applications. 2) Persistence ensures that data is not lost through RDB and AOF, and the choice is based on application needs.

    Redis's Server-Side Operations: What It OffersRedis's Server-Side Operations: What It OffersApr 29, 2025 am 12:21 AM

    Redis'sServer-SideOperationsofferFunctionsandTriggersforexecutingcomplexoperationsontheserver.1)FunctionsallowcustomoperationsinLua,JavaScript,orRedis'sscriptinglanguage,enhancingscalabilityandmaintenance.2)Triggersenableautomaticfunctionexecutionone

    Redis: Database or Server? Demystifying the RoleRedis: Database or Server? Demystifying the RoleApr 28, 2025 am 12:06 AM

    Redisisbothadatabaseandaserver.1)Asadatabase,itusesin-memorystorageforfastaccess,idealforreal-timeapplicationsandcaching.2)Asaserver,itsupportspub/submessagingandLuascriptingforreal-timecommunicationandserver-sideoperations.

    Redis: The Advantages of a NoSQL ApproachRedis: The Advantages of a NoSQL ApproachApr 27, 2025 am 12:09 AM

    Redis is a NoSQL database that provides high performance and flexibility. 1) Store data through key-value pairs, suitable for processing large-scale data and high concurrency. 2) Memory storage and single-threaded models ensure fast read and write and atomicity. 3) Use RDB and AOF mechanisms to persist data, supporting high availability and scale-out.

    Redis: Understanding Its Architecture and PurposeRedis: Understanding Its Architecture and PurposeApr 26, 2025 am 12:11 AM

    Redis is a memory data structure storage system, mainly used as a database, cache and message broker. Its core features include single-threaded model, I/O multiplexing, persistence mechanism, replication and clustering functions. Redis is commonly used in practical applications for caching, session storage, and message queues. It can significantly improve its performance by selecting the right data structure, using pipelines and transactions, and monitoring and tuning.

    Redis vs. SQL Databases: Key DifferencesRedis vs. SQL Databases: Key DifferencesApr 25, 2025 am 12:02 AM

    The main difference between Redis and SQL databases is that Redis is an in-memory database, suitable for high performance and flexibility requirements; SQL database is a relational database, suitable for complex queries and data consistency requirements. Specifically, 1) Redis provides high-speed data access and caching services, supports multiple data types, suitable for caching and real-time data processing; 2) SQL database manages data through a table structure, supports complex queries and transaction processing, and is suitable for scenarios such as e-commerce and financial systems that require data consistency.

    Redis: How It Acts as a Data Store and ServiceRedis: How It Acts as a Data Store and ServiceApr 24, 2025 am 12:08 AM

    Redisactsasbothadatastoreandaservice.1)Asadatastore,itusesin-memorystorageforfastoperations,supportingvariousdatastructureslikekey-valuepairsandsortedsets.2)Asaservice,itprovidesfunctionalitieslikepub/submessagingandLuascriptingforcomplexoperationsan

    See all articles

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    Video Face Swap

    Video Face Swap

    Swap faces in any video effortlessly with our completely free AI face swap tool!

    Hot Tools

    Atom editor mac version download

    Atom editor mac version download

    The most popular open source editor

    VSCode Windows 64-bit Download

    VSCode Windows 64-bit Download

    A free and powerful IDE editor launched by Microsoft

    WebStorm Mac version

    WebStorm Mac version

    Useful JavaScript development tools

    MantisBT

    MantisBT

    Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

    Zend Studio 13.0.1

    Zend Studio 13.0.1

    Powerful PHP integrated development environment