Redis 源碼簡潔剖析 14 - Redis 持久化

Redis 持久化方式

主要參考 Redis 官方文檔:Redis Persistence。共有 4 種持久化方式:

  • RDB (Redis Database):以指定的時間間隔執行數據在某個時間點的快照。
  • AOF (Append Only File):AOF 持久化記錄服務器接收到的每個寫操作。Redis server 在啓動時會重放這些操作,進而重建數據。記錄的命令與 Redis 協議的格式相同,並且是以追加的方式記錄。當日志變得太大時,Redis 能夠在後臺 重寫 日誌。
  • No persistence:用戶也可以完全禁用持久性,數據只在內存中使用。
  • RDB + AOF:可以在同一個實例中結合 AOF 和 RDB。在這種情況下,Redis 重啓時會使用 AOF 文件重建原始數據,因爲它是最完整的。

RDB

優勢

  • RDB 是 Redis 數據在某個時間點的文件,格式非常緊湊,非常適合作爲備份。比如我們可以在最近的 24 小時內,每小時歸檔一個 RDB 文件,並在 30 天內每天保存一次 RDB 快照。這樣我們可以輕鬆恢復不同版本的數據。
  • RDB 非常適合災難恢復,RDB 文件是可以傳輸的單個緊湊文件。
  • RDB 提升 Redis 的性能,因爲 Redis 父進程爲了持久化而做的唯一操作,就是派生一個將完成其餘所有操作的子進程。
  • 與 AOF 相比,RDB 在大數據集恢復時更迅速。

劣勢

  • RDB 在 Redis 宕機的情況下,更容易丟失數據。如果我們每 5 分鐘創建一次 RDB 快照,如果 Redis 沒有正常關閉,那最新幾分鐘的數據就會丟失。
  • RDB 需要經常 fork() 出在磁盤上持久化的子進程。在數據很大、CPU 性能不好時,會導致 Redis 在幾毫秒甚至一秒內不對外服務。

AOF

以獨立日誌的方式,記錄每次寫命令,重啓時再重新執行 AOF 文件中的命令,進而回複數據。相對於 RDB 的記錄數據,AOF 是記錄數據產生的過程

優勢

  • 服務宕機時丟失數據更少,比如僅丟失最後 1s 的數據。
  • AOF 日誌只是附加日誌,不會出現尋道問題,也不會在斷電時出現損壞。
  • AOF 日誌易於理解和解析,包含所有操作。

劣勢

  • AOF 文件比相同數據集的 RDB 文件大。
  • 取決於具體的 fsync 策略,AOF 可能比 RDB 慢。

Redis < 7.0

  • 在重新期間對數據庫的寫入,AOF 可能佔用大量內存(緩衝在內存中,並在最後寫入新的 AOF)。
  • 重寫期間,所有寫入的命令都會寫入磁盤兩次。

在 redis.conf 中,可以看到 appendfsync 有 3 個值:

  • no: don't fsync, just let the OS flush the data when it wants. Faster.
  • always: fsync after every write to the append only log. Slow, Safest.
  • everysec: fsync only one time every second. Compromise.
# The fsync() call tells the Operating System to actually write data on disk
# instead of waiting for more data in the output buffer. Some OS will really flush
# data on disk, some other OS will just try to do it ASAP.
#
# Redis supports three different modes:
#
# no: don't fsync, just let the OS flush the data when it wants. Faster.
# always: fsync after every write to the append only log. Slow, Safest.
# everysec: fsync only one time every second. Compromise.
#
# The default is "everysec", as that's usually the right compromise between
# speed and data safety. It's up to you to understand if you can relax this to
# "no" that will let the operating system flush the output buffer when
# it wants, for better performances (but if you can live with the idea of
# some data loss consider the default persistence mode that's snapshotting),
# or on the contrary, use "always" that's very slow but a bit safer than
# everysec.
#
# More details please check the following article:
# http://antirez.com/post/redis-persistence-demystified.html
#
# If unsure, use "everysec".

# appendfsync always
appendfsync everysec
# appendfsync no

參考鏈接

Redis 源碼簡潔剖析系列

最簡潔的 Redis 源碼剖析系列文章

Java 編程思想-最全思維導圖-GitHub 下載鏈接,需要的小夥伴可以自取~

原創不易,希望大家轉載時請先聯繫我,並標註原文鏈接。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章