Redis persistence
1. RDB(snapshotting)
Also the default.(Make a backup of the data, save the data to a file)
Snapshot is the default persistence mode. In this mode, data in memory is written to a binary file as a snapshot. The default file name is dump.rdb. You can configure the automatic snapshot persistence mode. We can configure Redis to make snapshots automatically if more than m key changes are made within n seconds.
The principle of data snapshot is to iterate all the data in the entire Redis memory and store it in a data file with the extension of RDB through the save command
You can call this procedure. The data snapshot configuration is as follows:
Save 900 1
Save 300 10
Save 60 10000
The above configuration in redis.conf indicates that data will be synchronized to the data file in how many update operations over a period of time. This can be combined with multiple conditions. Save is executed when a key changes in 900 seconds, 10 keys change in 300 seconds, and 10,000 keys change in 60 seconds.
Workflow of RDB persistence mechanism
(1) Redis tries to generate the RDB snapshot file according to the configuration
(2) fork a child process
(3) The child process tries to dump data into a temporary RDB snapshot file
(4) After the RDB snapshot file is generated, the old snapshot file is replaced
Dump. RDB, which overwrites the old snapshot each time a new snapshot is created
2. Append-onlyfile(aOF)
Aof mode: The snapshot mode is performed at a certain interval. If redis goes down unexpectedly, all changes made after the last snapshot will be lost. Aof has better persistence than snapshot because redis appends every write command it receives to a file using the write function when aOF is used. When Redis restarts, it re-executes the write command saved in the file to reconstruct the contents of the database in memory.
Of course, since the OS caches the changes made by write in the kernel, they may not be written to disk immediately. It is still possible to lose some changes in aOF persistence. The configuration file tells Redis when we want to force OS writes to disk through the fsync function.
Appendfsync no/always/everysec
“No” : wait for the operating system to synchronize data cache to disks. Performance is the best, persistence is not guaranteed.
Always: indicates that fsync() is manually called after each update operation to write data to disk. Write to disk immediately every time a write command is received, the slowest, but guarantees complete persistence.
Everysec: Synchronizes data every second. Forcing writes to disk once per second provides a good trade-off between performance and persistence.