search
HomeDatabaseRedisExample analysis of Redis persistence mechanism

Redis stores data in memory, and the data will be lost when the process exits. Through Redis's persistence mechanism, data in memory can be stored on disk, and data can be loaded from disk files to refill the memory after a restart.

Redis supports two persistence mechanisms: full mirror RDB and incremental persistence AOF.

RDB is a snapshot of Redis, which stores all unexpired key-value pairs in Redis.

Configure RDB in redis.conf:

dbfilename dump.rdb
dir /var/lib/redis



save 900 1 save 300 10 save 60 10000 save "" stop-writes-on-bgsave-error yes rdbcompression yes rdbchecksum yes

Every time the redis process starts, it will first check whether the rdb file exists, and if it exists, load the contents of the file. into memory.

When redis automatically updates the RDB file, it will fork a sub-process to perform snapshot saving. During the saving period, the main process can provide services normally.

We can also save the snapshot through the command:

  • save: Save the snapshot in a blocking manner, and redis cannot handle other requests during the save period

  • bgsave: Fork a child process to complete the saving work. The normal service of redis will not be affected during the saving period. The

lastsave command can get the latest RDB file creation timestamp, which can be used to check whether the save is successful.

RDB is a database snapshot, and each time it is created, the entire database needs to be written to the file. This is a very time-consuming operation, so it is difficult to perform frequently, and a large amount of data may be lost when an exception occurs.

Redis provides the incremental persistence tool AOF (Append Only ile). AOF performs persistence by recording all write instructions in the Redis database. Instructions are stored in the AOF file in the format of the Redis communication protocol.

When the Redis process starts, it will check whether the AOF file exists. If it exists, the instructions in the AOF will be executed sequentially to restore the data.

Redis will add a log to the AOF file every time it executes a write command, but the new record will not be written to disk immediately (fsync) but cached in the write buffer.

We can configure the strategy of writing the data in the buffer to disk to avoid data loss.

Writing data in the buffer to disk is a time-consuming operation. Frequent disk writing will affect performance, but Redis crashes and loses less data, so we need to make trade-offs based on application scenarios.

AOF may record redundant instructions. If we execute the set instruction 100 times for the same key, there will be 100 records in the AOF file but only the last set instruction will be retained to recover the data. AOF rewriting will organize the AOF file, clean up unnecessary command logs (such as deleting overwritten set commands), and reduce the size of the AOF file.

redis adopts a background rewriting strategy, that is, forking a child process to write the sorted AOF into a temporary file. Use BGREWRITEAOF to manually trigger the background rewrite operation.

Actually AOF rewriting will not read the original AOF file. The child process will have a copy of the current data and directly generate a new AOF file based on the copy.

During the rewriting period, the main process writes the new write operations into the original AOF file and AOF rewrite cache. Even if the rewriting fails, the original AOF file still saves complete data. When the child process completes AOF rewriting, it will send a signal to the main process. After receiving the signal, the main process will write the contents of the AOF rewriting cache into a new AOF file, and then overwrite the original file with the new AOF file.

Configure AOF in redis.conf:

appendonly yes  
  

appendfilename appendonly.aof  
  


appendfsync everysec 

    no-appendfsync-on-rewrite no   
  


auto-aof-rewrite-percentage 100  
  

auto-aof-rewrite-min-size 64mb

Redis will record the size of the AOF file at startup or after the last rewrite. If the size of the new data reaches 100% of the original size (auto-aof-rewrite-percentage configuration) triggers rewriting.

The rewrite operation will only be performed when the current AOF file size is greater than auto-aof-rewrite-min-size. Otherwise, rewriting will not be performed even if the amount of new data exceeds the specified percentage. This avoids the problem of frequent initial rewriting caused by the original file being too small.

The above is the detailed content of Example analysis of Redis persistence mechanism. 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'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

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.

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

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

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