search
HomeDatabaseRedisHow Redis implements persistence solution (used by RDB and AOF)

1. The role of persistence

1. What is persistence

All data saved by redis In memory, updates to data will be asynchronously saved to the hard disk

2. How to implement persistence

Snapshot: a completion of data at a certain time Backup - mysql's Dump - redis's RDB log writing: any operation is recorded in the log. To restore the data, just go through the log again - mysql's Binlog - Hhase's HLog - Redis's AOF

2. RDB

1. What is RDB

How Redis implements persistence solution (used by RDB and AOF)

2. Trigger Mechanism-main three methods

The first one: save (synchronization)

1 The client enters the save command----》redis server----》Synchronized creation RDB binary file

2 will cause redis blocking (when the amount of data is very large)

3 File strategy: If the old RDB exists, it will replace the old one

4 Complexity o(n)

Second type: bgsave (asynchronous, Backgroud saving started)

1 The client enters the save command----"redis server----"asynchronous Create an RDB binary file (the fork function generates a child process (fork will block reids), execute createRDB, the execution is successful, and a reids message is returned)

2 When accessing redis at this time, the client will respond normally

3 File strategy: Same as save, if the old RDB exists, it will replace the old one

4 Complexity o(n)

The third method: (common method) (** ****) Automatically (through configuration file)
Configuration seconds changes
save 900 1save 300 10save 60 10000If 1w pieces of data are changed in 60s, automatically generate rdb
If 10 pieces of data are changed in 300s , automatically generate rdb
If 1 piece of data is changed in 900s, automatically generate rdb

If any of the above three conditions is met, the rdb will be automatically generated, and bgsave is used internally

#Configuration:

save 900 1 #Configure one

save 300 10 #Configure one

save 60 10000 #Configure one

dbfilename dump.rdb #The name of the rdb file, the default is dump.rdb

dir ./ #The rdb file exists in the current directory

stop-writes-on-bgsave-error yes #If an error occurs in bgsave, whether to stop Write, the default is yes

rdbcompression yes #Use compression format

rdbchecksum yes #Whether to checksum the rdb file

#Best configuration

save 900 1

save 300 10

save 60 10000 dbfilename dump-${port}.rdb

#With port As the file name, there may be many reids on one machine, so it will not be messy

dir /bigdiskpath #Put the save path to a large hard disk location directory

stop-writes-on-bgsave-error yes

#Error stop

rdbcompression yes #Compression

rdbchecksum yes #Verification

RDB trigger mechanism generally uses the first There are three ways, but this method also has shortcomings. If the number of modified items is not within the setting range, it will not be triggered, which will lead to a lot of data not being persisted. So we generally use the following method: AOF.

If you want to save unimportant data, you can use RDB (such as cache data). If you want to save very important data, you should use AOF, but both methods can also be used at the same time.

3. AOF

1. RDB problem

is time consuming and performance consuming. Uncontrollable, data may be lost.

2. AOF introduction

Every time the client writes a command, a log is recorded and placed in the log file. If there is a downtime, the data can be completely restored

3. Three strategies of AOF

The log is not written directly to the hard disk, but is first placed in the buffer. The buffer is written to the hard disk according to some strategies

#The first type: always: redis--》Write command refresh buffer---》Fsync each command to the hard disk---》AOF file

#The second type: everysec (default value ): redis——》Buffer refreshed by writing command---》fsync buffer to hard disk every second--》AOF file

#The third type: no:redis——》Buffer refreshed by writing command Buffer---》The operating system determines, the buffer fsyncs to the hard disk--》AOF file

Command always everysec no
Advantages No data loss
Once fsync per second, lose 1 second of data Don’t worry
Disadvantages
The IO overhead is large, and the average sata disk only has a few hundred TPS lost 1 second data Uncontrollable

4.AOF rewriting

As the commands are gradually written, the amount of concurrency increases , the AOF file will become larger and larger, solve this problem through AOF rewriting

##set hello world
##The essence is to optimize expired, useless, repeated, and optimizable commands, which can reduce disk usage and accelerate recovery speedImplementation method
Native AOF ##AOF Rewrite

set hello java

set hello hehe

incr counter

ncr counter

rpush mylist a

rpush mylist b

rpush mylist c

Expired data

##set hello hehe
set counter 2

rpush mylist a b c


bgrewriteaof: The client sends the bgrewriteaof command to the server, and the server will start a fork process to complete the AOF rewrite

AOF rewrite configuration:


Rewrite process

AOF configuration file (******)

How Redis implements persistence solution (used by RDB and AOF)appendonly yes #Set this option to yes and open appendfilename "appendonly-${port}.aof " #The name of the file saved appendfsync everysec #Adopt the second strategy dir /bigdiskpath #The storage path no-appendfsync-on-rewrite yes #When rewriting aof, whether to do the append operation of aof, because aof rewriting consumes Performance, disk consumption, normal AOF writing to disk has certain conflicts, data during this period is allowed to be lost

4. Selection of RDB and AOF

1. Comparison of rdb and aof

CommandLow High (hang and restart, aof data will be loaded) Small Large FastLost data Decided according to strategy Heavy Light
rdb aof Startup priority


Size


Recovery speed

Slow

Data security



Light and heavy



2.rdb best strategy

Rdb is turned off, master-slave operation
Centralized management: backup data by day, by hour
Master-slave configuration, slave node is turned on

3.aof best strategy

Open: cache and storage, open in most cases,
aof rewrite centralized management
everysec: strategy refreshed every second

4. Best strategy

Small sharding: the maximum memory of each redis is 4g
Cache or storage: use different strategies according to the characteristics
Monitor the hard disk at all times, Memory, load network, etc.
Have enough memory

The above is the entire content of Redis (4)-persistence solution (used by RDB and AOF).

Related references:PHP Chinese website

The above is the detailed content of How Redis implements persistence solution (used by RDB and AOF). For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:51dev. If there is any infringement, please contact admin@php.cn delete
Is Redis a SQL or NoSQL Database? The Answer ExplainedIs Redis a SQL or NoSQL Database? The Answer ExplainedApr 18, 2025 am 12:11 AM

RedisisclassifiedasaNoSQLdatabasebecauseitusesakey-valuedatamodelinsteadofthetraditionalrelationaldatabasemodel.Itoffersspeedandflexibility,makingitidealforreal-timeapplicationsandcaching,butitmaynotbesuitableforscenariosrequiringstrictdataintegrityo

Redis: Improving Application Performance and ScalabilityRedis: Improving Application Performance and ScalabilityApr 17, 2025 am 12:16 AM

Redis improves application performance and scalability by caching data, implementing distributed locking and data persistence. 1) Cache data: Use Redis to cache frequently accessed data to improve data access speed. 2) Distributed lock: Use Redis to implement distributed locks to ensure the security of operation in a distributed environment. 3) Data persistence: Ensure data security through RDB and AOF mechanisms to prevent data loss.

Redis: Exploring Its Data Model and StructureRedis: Exploring Its Data Model and StructureApr 16, 2025 am 12:09 AM

Redis's data model and structure include five main types: 1. String: used to store text or binary data, and supports atomic operations. 2. List: Ordered elements collection, suitable for queues and stacks. 3. Set: Unordered unique elements set, supporting set operation. 4. Ordered Set (SortedSet): A unique set of elements with scores, suitable for rankings. 5. Hash table (Hash): a collection of key-value pairs, suitable for storing objects.

Redis: Classifying Its Database ApproachRedis: Classifying Its Database ApproachApr 15, 2025 am 12:06 AM

Redis's database methods include in-memory databases and key-value storage. 1) Redis stores data in memory, and reads and writes fast. 2) It uses key-value pairs to store data, supports complex data structures such as lists, collections, hash tables and ordered collections, suitable for caches and NoSQL databases.

Why Use Redis? Benefits and AdvantagesWhy Use Redis? Benefits and AdvantagesApr 14, 2025 am 12:07 AM

Redis is a powerful database solution because it provides fast performance, rich data structures, high availability and scalability, persistence capabilities, and a wide range of ecosystem support. 1) Extremely fast performance: Redis's data is stored in memory and has extremely fast read and write speeds, suitable for high concurrency and low latency applications. 2) Rich data structure: supports multiple data types, such as lists, collections, etc., which are suitable for a variety of scenarios. 3) High availability and scalability: supports master-slave replication and cluster mode to achieve high availability and horizontal scalability. 4) Persistence and data security: Data persistence is achieved through RDB and AOF to ensure data integrity and reliability. 5) Wide ecosystem and community support: with a huge ecosystem and active community,

Understanding NoSQL: Key Features of RedisUnderstanding NoSQL: Key Features of RedisApr 13, 2025 am 12:17 AM

Key features of Redis include speed, flexibility and rich data structure support. 1) Speed: Redis is an in-memory database, and read and write operations are almost instantaneous, suitable for cache and session management. 2) Flexibility: Supports multiple data structures, such as strings, lists, collections, etc., which are suitable for complex data processing. 3) Data structure support: provides strings, lists, collections, hash tables, etc., which are suitable for different business needs.

Redis: Identifying Its Primary FunctionRedis: Identifying Its Primary FunctionApr 12, 2025 am 12:01 AM

The core function of Redis is a high-performance in-memory data storage and processing system. 1) High-speed data access: Redis stores data in memory and provides microsecond-level read and write speed. 2) Rich data structure: supports strings, lists, collections, etc., and adapts to a variety of application scenarios. 3) Persistence: Persist data to disk through RDB and AOF. 4) Publish subscription: Can be used in message queues or real-time communication systems.

Redis: A Guide to Popular Data StructuresRedis: A Guide to Popular Data StructuresApr 11, 2025 am 12:04 AM

Redis supports a variety of data structures, including: 1. String, suitable for storing single-value data; 2. List, suitable for queues and stacks; 3. Set, used for storing non-duplicate data; 4. Ordered Set, suitable for ranking lists and priority queues; 5. Hash table, suitable for storing object or structured data.

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor