search
HomeDatabaseRedisThis article will take you to understand the complete version of Redis persistence.

This article explains the knowledge points Introduction to persistence RDB AOF The difference between RDB and AOF Persistence application scenarios

Preface

Kaka compiled a roadmap to create an interview guide, and prepared to write articles according to this roadmap. Later, I found that I was adding knowledge points that were not supplemented. I also look forward to your partners joining in to help add some information. See you in the comments section!

This article will take you to understand the complete version of Redis persistence.
Insert image description here

Demo environment

centos7.0 redis4.0 redis storage directory:/usr/local/redis redis.conf storage directory:/usr/local/redis/data

1. Introduction to persistence

All data in redis is stored in memory. If redis crashes, the data will be lost. Redis persistence is to save data on disk. The working mechanism that uses permanent storage media to save data processes and restore the saved data at a specific time is called persistence.

What is saved in the persistence process?

The first snapshot form stores data results and focuses on the data, which is the RDB discussed below

The second operation process stores the operation process. The storage structure is complex and the focus is The point is the data operation process, which is the AOF

#2 discussed below. RDB

##2-1 RDB startup mode -- save command

The following figure is the configuration information of redis.conf. After executing save, a The file of dump.rdb

Now we set a value and then save it. There will be a file of dump6379.rdb under /usr/local/redis/dataThis article will take you to understand the complete version of Redis persistence.This article will take you to understand the complete version of Redis persistence.

2-2 RDB startup mode -- save command related configuration

  • dbfilename dump6379.rdb: Set the local database file name, the default value is dump.rdb
  • dir: The path to store the rdb file
  • rdbcompression yes: Set the storage to local Whether to compress data in the database, the default is yes, using lzf compression
  • rdbchecksum yes: Set whether to process RDB file format verification, the verification process is performed during both writing and reading files.

2-3 RDB data recovery

In fact, this data recovery is different from other relationships There is basically no need to do anything to restore a large database. Just restart it

2-4 RDB -- How the save command works

This picture Sourced from online videos. The execution of the save command will block the current redis server until the current RDB process is completed, which may cause long-term blocking. This command is basically abandoned and no longer used during the work process. Will replace all This article will take you to understand the complete version of Redis persistence.

with bgsave

2-5 RDB -- Working principle of bgsave instruction

This article will take you to understand the complete version of Redis persistence.When bgsave is executed in redis, it will return directly A Background saving started

At this time we are taking a look at the log file. The bgsave command is optimized for the save blocking problemThis article will take you to understand the complete version of Redis persistence.

##2-5 RDB -- Configuration file auto-start
<span style="display: block; background: url(https://my-wechat.mdnice.com/point.png); height: 30px; width: 100%; background-size: 40px; background-repeat: no-repeat; background-color: #272822; margin-bottom: -7px; border-radius: 5px; background-position: 10px 10px;"></span><code class="hljs" style="overflow-x: auto; padding: 16px; color: #ddd; display: -webkit-box; font-family: Operator Mono, Consolas, Monaco, Menlo, monospace; font-size: 12px; -webkit-overflow-scrolling: touch; letter-spacing: 0px; padding-top: 15px; background: #272822; border-radius: 5px;"><span class="hljs-selector-tag" style="color: #f92672; font-weight: bold; line-height: 26px;">save</span> 900 1<br/><span class="hljs-selector-tag" style="color: #f92672; font-weight: bold; line-height: 26px;">save</span> 300 10<br/><span class="hljs-selector-tag" style="color: #f92672; font-weight: bold; line-height: 26px;">save</span> 60 10000<br/><span class="hljs-selector-tag" style="color: #f92672; font-weight: bold; line-height: 26px;">stop-writes-on-bgsave-error</span> <span class="hljs-selector-tag" style="color: #f92672; font-weight: bold; line-height: 26px;">yes</span><br/></code>

save [Time] [Number of key changes]This article will take you to understand the complete version of Redis persistence.

That is to say, there are 10 in 300 seconds If the key value changes, bgsave

will be executed in the background.

3. AOF

##3-1 AOF concept

AOF persistence: Record each write command in an independent log, and re-execute the commands in the AOF file during restart to achieve data recovery. Compared with RDB, it can be simply described as the process of recording data generation

The main function of AOF is to solve the real-time nature of data persistence, and it is currently the mainstream method of redis persistence

3-2 AOF data writing process

Execute a redis commandThis article will take you to understand the complete version of Redis persistence.

redis’s AOF will refresh the command buffer Area

Then synchronize to the .aof file configured in redis.conf according to certain policies

3-3 Three strategies for AOF writing data

  • always: every write operation are synchronized to the AOF file, with zero data error and low performance. It is not recommended to use
  • everysec: Synchronize the instructions in the buffer to the AOF file every second, and the data accuracy is relatively low. High, with higher performance, is recommended and is also the default configuration.However, if the system suddenly crashes, the data within 1 second will be lost.
  • no: The operating system controls the cycle of each synchronization to the AOF file, and the overall process is uncontrollable

3-4 AOF function enabled

  • Configuration: appendonly yes|no
  • Function: Whether to enable AOF persistence function, the default is not enabled
  • Configuration: appendfsync always| everysec | no
  • Function: AOF write data strategy
  • Configuration: appenfilename filename
  • Function: AOF persistence file name, the default name is appendonly.aof

This article will take you to understand the complete version of Redis persistence. Then use restart the redis service, you can use it in usr/local/redis/data You can see the appendonly.aof file in the directoryThis article will take you to understand the complete version of Redis persistence.Then we execute a command on the redis client and check it out. You can see that the data will be stored in the appendonly.aof file. This article will take you to understand the complete version of Redis persistence.

3-5 Problems with AOF writing data

Let’s look at a case first. After we repeatedly set the name key , open the appendonly.aof file to view, you can see that there are three operations, but these three operations are all modified by one key! Can't we only save the last key? With this question, we continue to look downThis article will take you to understand the complete version of Redis persistence.

3-6 AOF rewriting

As commands continue to be written to AOF, the file will become larger and larger. In order to solve this problem, redis introduces the AOF rewriting mechanism to compress the file size. AOF file rewriting is the process of converting data in the redis process into write commands and synchronizing them to the new AOF file. Simply put, it converts the execution results of several commands on the same data into the execution records of the instructions corresponding to the final result data.

For example, we executed the set name command three times above, but in the end we only need the data of the last execution. That is, we only need the last execution record.

3-7 AOF rewriting function

  • Reduce disk usage and improve disk utilization
  • Improve persistence efficiency, reduce persistence write time, and improve IO performance
  • Reduce data recovery time and improve data recovery efficiency

3-8 AOF rewrite rules

  • The process has timed out Data is no longer written to the file
  • Ignore invalid instructions and use in-process data to generate directly during rewriting, so that the new AOF file value retains the final data writing command. Such as del instruction, hdel, srem. Set a key value multiple times, etc.
  • Multiple write commands for the same data are merged into one command: such as lpush list a lpush lsit b lpush list c can be converted For lpush list a b c.However, in order to prevent client buffer overflow caused by excessive data volume, each instruction of list, set, hash, zset types can write up to 64 elements

3-9 AOF manual rewriting

Command: bgrewriteaof

Then we 3- For the question 5, we execute the bgrewriteaof command on the command line and then check the appendonly.aof file

After the execution, we will find that the file has become smaller and there is only one command in the file

This article will take you to understand the complete version of Redis persistence.
Insert picture description here

3-10 AOF manual rewriting working principle

This article will take you to understand the complete version of Redis persistence.
Insert image description here

3-11 AOF automatic rewrite

Configuration: auto-aof-rewrite-percentage 100 | auto-aof-rewrite-min-size 64mbTrigger comparison parameters: aof_current_size | aof_base_size

When aof_current_size > auto-aof-rewrite-min-size 64mb will start rewriting

This picture comes from the Internet

3-11 AOF workflow and rewrite flow = process

This article will take you to understand the complete version of Redis persistence.This article will take you to understand the complete version of Redis persistence.

##4. The difference between RDB and AOF

  • ## is very sensitive to data, it is recommended to use the default AOF Persistence solution

      AOF persistence strategy uses everysecond, fsync-times per second • This strategy redis can still maintain good processing performance. When a problem occurs, up to 0- Data within 1 second.
    • Note: Due to the large storage size of AO files and the slow recovery speed
  • Validity of data presentation stage, it is recommended to use RDB persistence solution

      The data can be well maintained without loss during the stage (this stage is for developers to operate and maintain Manually maintained), and the recovery speed is faster. The RDB solution is usually used for stage point data recovery
    • Note: Using RDB to achieve tight data persistence will cause Redis to drop very low
  • Comprehensive comparison
    • The choice between RDB and AOF is actually a trade-off, each has advantages and disadvantages
    • If you cannot bear data loss within a few minutes , very sensitive to industry data, choose A0F
    • . If you can withstand data loss within a few minutes, if you pursue the recovery speed of large data sets, choose RDB
    • Use RDB for disaster recovery
    • Double insurance strategy, start RDB and AOF at the same time. After restarting, Redis gives priority to using A0F to recover data, reducing the amount of lost data
    ##❝Persistence in learning, persistence in blogging, and persistence in sharing are the beliefs that Kaka has always adhered to since his career. I hope that Kaka’s articles can be seen in the huge Internet Bringing you a little help. See you in the next issue.

## Recommended: "
redis tutorial

The above is the detailed content of This article will take you to understand the complete version of Redis persistence.. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
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

Redis vs. Other Databases: A Comparative AnalysisRedis vs. Other Databases: A Comparative AnalysisApr 23, 2025 am 12:16 AM

Compared with other databases, Redis has the following unique advantages: 1) extremely fast speed, and read and write operations are usually at the microsecond level; 2) supports rich data structures and operations; 3) flexible usage scenarios such as caches, counters and publish subscriptions. When choosing Redis or other databases, it depends on the specific needs and scenarios. Redis performs well in high-performance and low-latency applications.

Redis's Role: Exploring the Data Storage and Management CapabilitiesRedis's Role: Exploring the Data Storage and Management CapabilitiesApr 22, 2025 am 12:10 AM

Redis plays a key role in data storage and management, and has become the core of modern applications through its multiple data structures and persistence mechanisms. 1) Redis supports data structures such as strings, lists, collections, ordered collections and hash tables, and is suitable for cache and complex business logic. 2) Through two persistence methods, RDB and AOF, Redis ensures reliable storage and rapid recovery of data.

Redis: Understanding NoSQL ConceptsRedis: Understanding NoSQL ConceptsApr 21, 2025 am 12:04 AM

Redis is a NoSQL database suitable for efficient storage and access of large-scale data. 1.Redis is an open source memory data structure storage system that supports multiple data structures. 2. It provides extremely fast read and write speeds, suitable for caching, session management, etc. 3.Redis supports persistence and ensures data security through RDB and AOF. 4. Usage examples include basic key-value pair operations and advanced collection deduplication functions. 5. Common errors include connection problems, data type mismatch and memory overflow, so you need to pay attention to debugging. 6. Performance optimization suggestions include selecting the appropriate data structure and setting up memory elimination strategies.

Redis: Real-World Use Cases and ExamplesRedis: Real-World Use Cases and ExamplesApr 20, 2025 am 12:06 AM

The applications of Redis in the real world include: 1. As a cache system, accelerate database query, 2. To store the session data of web applications, 3. To implement real-time rankings, 4. To simplify message delivery as a message queue. Redis's versatility and high performance make it shine in these scenarios.

Redis: Exploring Its Features and FunctionalityRedis: Exploring Its Features and FunctionalityApr 19, 2025 am 12:04 AM

Redis stands out because of its high speed, versatility and rich data structure. 1) Redis supports data structures such as strings, lists, collections, hashs and ordered collections. 2) It stores data through memory and supports RDB and AOF persistence. 3) Starting from Redis 6.0, multi-threaded I/O operations have been introduced, which has improved performance in high concurrency scenarios.

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

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.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools