search
HomeDatabaseRedisSeveral ways of Redis persistence

Several ways of Redis persistence

Nov 28, 2019 pm 04:57 PM
redisEndurance

Redis reads and writes in memory, so its performance is high, but the data in the memory will be lost as the server restarts. In order to ensure that the data is not lost, we need to move the data in the memory to The data is stored on the disk so that the original data can be restored from the disk when Redis is restarted, and the whole process is called Redis persistence.

Several ways of Redis persistence

Redis persistence is also one of the main differences between Redis and Memcached , because Memcached is not With persistence function.

1. Several persistence methods

Redis persistence has the following three methods:

Snapshot method (RDB, Redis DataBase) will The memory data at a certain moment is written to the disk in binary form;

File append mode (AOF, Append Only File) records all operation commands and appends them to the file in the form of text;

Hybrid persistence method, a new method added after Redis 4.0. Hybrid persistence combines the advantages of RDB and AOF. When writing, the current data is first written to the beginning of the file in the form of RDB. Then store the subsequent operation commands in the file in AOF format, which can not only ensure the speed of Redis restart, but also reduce the risk of data loss.

Because each persistence solution has specific usage scenarios, let’s start with RDB persistence.

2. Introduction to RDB

RDB (Redis DataBase) is the process of writing a memory snapshot (Snapshot) at a certain moment to the disk in binary form.

3. Persistence triggering

There are two types of persistence triggering methods for RDB: one is manual triggering, and the other is automatic triggering.

1) Manual trigger

There are two operations to manually trigger persistence: save and bgsave. The main difference between them is: whether to block the execution of the Redis main thread.

① save command

Executing the save command in the client will trigger the persistence of Redis, but at the same time, it will also put Redis in a blocking state until the RDB is persisted. It will not respond to commands sent by other clients until it is completed, so it must be used with caution in a production environment. The

save command is used as follows:

Several ways of Redis persistence
As can be seen from the picture, after the save command is executed, the persistent file dump. The modification time of rdb has changed, which means that save has successfully triggered RDB persistence.
save command execution process, as shown in the figure below:

Several ways of Redis persistence

② bgsave command

bgsave (background save) both background The meaning of saving, the biggest difference between it and the save command is that bgsave will fork() a child process to perform persistence. During the whole process, there is only a short blocking when fork() the child process. After the child process is created, Redis The main process can respond to requests from other clients. Compared with the save command that blocks the entire process, the bgsave command is obviously more suitable for us to use.

bgsave command is used, as shown in the figure below:

Several ways of Redis persistence
bgsave execution process, as shown in the figure below:

Several ways of Redis persistence

2) Automatic trigger

After talking about the manual triggering method of RDB, let’s look at how to automatically trigger RDB persistence?
RDB automatic persistence mainly comes from the following situations.

① save m n

save m n means that if n keys change within m seconds, persistence will be automatically triggered.
The parameters m and n can be found in the Redis configuration file. For example, save 60 1 indicates that if at least one key changes within 60 seconds, RDB persistence will be triggered.
Automatically trigger persistence. The essence is that Redis will automatically execute a bgsave command if the set trigger conditions are met.

Note: When setting multiple save m n commands, persistence will be triggered if any condition is met.

For example, we have set the following two save m n commands:

save 60 10save 600 1

If the Redis key value changes 10 times within 60s, persistence will be triggered; if the Redis key value changes within 60s If the value changes less than 10 times, Redis will determine whether the Redis key value has been modified at least once within 600s, and if so, persistence will be triggered.

② flushall

flushall 命令用于清空 Redis 数据库,在生产环境下一定慎用,当 Redis 执行了 flushall 命令之后,则会触发自动持久化,把 RDB 文件清空。

执行结果如下图所示:

Several ways of Redis persistence

③ 主从同步触发

在 Redis 主从复制中,当从节点执行全量复制操作时,主节点会执行 bgsave 命令,并将 RDB 文件发送给从节点,该过程会自动触发 Redis 持久化。

4.配置说明

合理的设置 RDB 的配置,可以保障 Redis 高效且稳定的运行,下面一起来看 RDB 的配置项都有哪些?

RDB 配置参数可以在  Redis 的配置文件中找见,具体内容如下:

# RDB 保存的条件
save 900 1
save 300 10
save 60 10000

# bgsave 失败之后,是否停止持久化数据到磁盘,yes 表示停止持久化,no 表示忽略错误继续写文件。
stop-writes-on-bgsave-error yes

# RDB 文件压缩
rdbcompression yes

# 写入文件和读取文件时是否开启 RDB 文件检查,检查是否有无损坏,如果在启动是检查发现损坏,则停止启动。
rdbchecksum yes

# RDB 文件名
dbfilename dump.rdb

# RDB 文件目录
dir ./

其中比较重要的参数如下列表:

① save 参数

它是用来配置触发 RDB 持久化条件的参数,满足保存条件时将会把数据持久化到硬盘。
默认配置说明如下:

save 900 1:表示 900 秒内如果至少有 1 个 key 值变化,则把数据持久化到硬盘;save 300 10:表示 300 秒内如果至少有 10 个 key 值变化,则把数据持久化到硬盘;save 60 10000:表示 60 秒内如果至少有 10000 个 key 值变化,则把数据持久化到硬盘。

② rdbcompression 参数

它的默认值是 yes 表示开启 RDB 文件压缩,Redis 会采用 LZF 算法进行压缩。如果不想消耗 CPU 性能来进行文件压缩的话,可以设置为关闭此功能,这样的缺点是需要更多的磁盘空间来保存文件。

③ rdbchecksum 参数

它的默认值为 yes 表示写入文件和读取文件时是否开启 RDB 文件检查,检查是否有无损坏,如果在启动是检查发现损坏,则停止启动。

5.配置查询

Redis 中可以使用命令查询当前配置参数。查询命令的格式为:config get xxx ,例如,想要获取 RDB 文件的存储名称设置,可以使用 config get dbfilename ,执行效果如下图所示:

Several ways of Redis persistence
查询 RDB 的文件目录,可使用命令 config get dir ,执行效果如下图所示:

Several ways of Redis persistence

6.配置设置

设置 RDB 的配置,可以通过以下两种方式:

● 手动修改 Redis 配置文件;

● 使用命令行设置,例如,使用 config set dir "/usr/data" 就是用于修改 RDB 的存储目录。

注意:手动修改 Redis 配置文件的方式是全局生效的,即重启 Redis 服务器设置参数也不会丢失,而使用命令修改的方式,在 Redis 重启之后就会丢失。但手动修改 Redis 配置文件,想要立即生效需要重启 Redis 服务器,而命令的方式则不需要重启 Redis 服务器。

小贴士:Redis 的配置文件位于 Redis 安装目录的根路径下,默认名称为 redis.conf。

7.RDB 文件恢复

当 Redis 服务器启动时,如果 Redis 根目录存在 RDB 文件 dump.rdb,Redis 就会自动加载 RDB 文件恢复持久化数据。

如果根目录没有 dump.rdb 文件,请先将 dump.rdb 文件移动到 Redis 的根目录。

验证 RDB 文件是否被加载

Redis 在启动时有日志信息,会显示是否加载了 RDB 文件,我们执行 Redis 启动命令:src/redis-server redis.conf ,如下图所示:
Several ways of Redis persistence
从日志上可以看出, Redis 服务在启动时已经正常加载了 RDB 文件。

小贴士:Redis 服务器在载入 RDB 文件期间,会一直处于阻塞状态,直到载入工作完成为止。

8.RDB 优缺点

1)RDB 优点

● RDB 的内容为二进制的数据,占用内存更小,更紧凑,更适合做为备份文件;

● RDB is very useful for disaster recovery. It is a compact file that can be transferred to a remote server faster for Redis service recovery;

● RDB can increase the running speed of Redis to a greater extent. Because the Redis main process will fork() a child process every time it is persisted to persist the data to the disk, the Redis main process will not perform operations such as disk I/O;

● and AOF format files In comparison, RDB files can be restarted faster.

2) Disadvantages of RDB

● Because RDB can only save data for a certain time interval, if the Redis service is accidentally terminated midway, the Redis data for a period of time will be lost;

● RDB requires frequent fork() to use child processes to persist it on disk. Fork() can be time-consuming if the data set is large, and can cause Redis to stop serving clients for a few milliseconds or even a second if the data set is large and CPU performance is poor.

9. Disabling persistence

Disabling persistence can improve the execution efficiency of Redis. If you are not sensitive to data loss, you can connect the client , execute the <span style="background-color: rgb(253, 234, 218); color: rgb(255, 0, 0);">config set save ""</span> command to disable Redis persistence, as shown in the following figure:

Several ways of Redis persistence

10. Summary

We can learn from this article that RDB persistence is divided into two methods: manual triggering and automatic triggering. Its advantage is that the storage file is small and Redis starts. It is faster to recover data, but the disadvantage is the risk of data loss. Restoring RDB files is also very simple. You only need to put the RDB files in the root directory of Redis, and the data will be automatically loaded and restored when Redis starts.

For more Redis related knowledge, please visit the Redis usage tutorial column!

The above is the detailed content of Several ways of Redis persistence. 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: 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.

How to implement redis counterHow to implement redis counterApr 10, 2025 pm 10:21 PM

Redis counter is a mechanism that uses Redis key-value pair storage to implement counting operations, including the following steps: creating counter keys, increasing counts, decreasing counts, resetting counts, and obtaining counts. The advantages of Redis counters include fast speed, high concurrency, durability and simplicity and ease of use. It can be used in scenarios such as user access counting, real-time metric tracking, game scores and rankings, and order processing counting.

How to use the redis command lineHow to use the redis command lineApr 10, 2025 pm 10:18 PM

Use the Redis command line tool (redis-cli) to manage and operate Redis through the following steps: Connect to the server, specify the address and port. Send commands to the server using the command name and parameters. Use the HELP command to view help information for a specific command. Use the QUIT command to exit the command line tool.

How to build the redis cluster modeHow to build the redis cluster modeApr 10, 2025 pm 10:15 PM

Redis cluster mode deploys Redis instances to multiple servers through sharding, improving scalability and availability. The construction steps are as follows: Create odd Redis instances with different ports; Create 3 sentinel instances, monitor Redis instances and failover; configure sentinel configuration files, add monitoring Redis instance information and failover settings; configure Redis instance configuration files, enable cluster mode and specify the cluster information file path; create nodes.conf file, containing information of each Redis instance; start the cluster, execute the create command to create a cluster and specify the number of replicas; log in to the cluster to execute the CLUSTER INFO command to verify the cluster status; make

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)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool