Stories

Detail Return Return

【趙渝強老師】Redis數據的遷移 - Stories Detail

通過使用Redis的鍵遷移功能,可以把數據從一個Redis數據庫中遷移到另一個數據庫中,例如從生產環境遷移到測試環境。Redis提供了move、dump+restore和migrate三種不同的方式來實現鍵的遷移。視頻講解如下:
https://www.bilibili.com/video/BV1j32wB2Es6/?aid=115503012058...

一、 使用move命令實現數據的內部遷移

下面通過具體的示例來演示move命令的使用。
(1)查看move命令的幫助信息。

127.0.0.1:6379> help move
MOVE key db
summary: Move a key to another database
since: 1.0.0
group: generic

(2)使用move命令移動鍵。

127.0.0.1:6379> move mykey1 3
(integer) 1

(3)切換到3號數據庫中查看鍵。

127.0.0.1:6379> select 3
OK
127.0.0.1:6379[3]> keys *
1) "mykey1"
127.0.0.1:6379[3]>

二、 使用dump+restore實現實例間數據的遷移

dump+restore可以實現在不同的Redis實例之間進行數據遷移的功能,整個遷移的過程分為兩步:首先,在源Redis數據庫實例上,dump命令會採用的是RDB格式將鍵值序列化;其次,在目標Redis數據庫實例上,restore命令將dump命令生成的鍵值執行反序列化進行復原。下面通過具體的示例來進行演示
(1)通過help命令查看dump命令的幫助信息。

127.0.0.1:6379> help dump
DUMP key
summary: Return a serialized version of the value stored at 
the specified key.
since: 2.6.0
group: generic

(2)在源Redis數據庫實例上插入數據,並使用dump命令進行持久化。

127.0.0.1:6379> set hello world
OK
127.0.0.1:6379> dump hello
"x00x05worldtx00xc9#mHx84/x11s"

(3)通過help命令查看restore命令的幫助信息。

127.0.0.1:6379> help restore
RESTORE key ttl serialized-value [REPLACE] [ABSTTL] [IDLETIME seconds] [FREQ frequency]
summary: Create a key using the provided serialized value, 
previously obtained using DUMP.
since: 2.6.0
group: generic

# 其中:ttl參數代表數據的過期時間。當ttl為0時,表示數據永遠不過期。

(4)在目標Redis數據庫實例上使用restore命令恢復數據。

127.0.0.1:6379> restore hello 0 "x00x05worldtx00xc9#mHx84/x11s"
OK
127.0.0.1:6379> get hello
"world"

三、 使用migrate實現實例間數據的遷移

migrate命令也可以用於在Redis數據庫實例之間進行數據遷移的。實際上migrate命令就是將dump、restore、del三個命令進行組合,從而簡化了操作流程。migrate命令具有原子性,並且從Redis3.0.6版本開始支持遷移多個鍵的功能,有效地提高了遷移效率。下面通過一個具體的示例來演示migrate命令的使用。
(1)使用help命令查看migrate命令的幫助信息。

127.0.0.1:6379> help migrate
MIGRATE host port key| destination-db timeout [COPY] [REPLACE] [AUTH password] [AUTH2 username password] [KEYS key]
summary: Atomically transfer a key from a Redis instance to another one.
since: 2.6.0
group: generic

(2)從源Redis數據庫實例上遷移鍵到目標Redis數據庫實例。

127.0.0.1:6379> migrate 192.168.79.12 6379 hello 0 1000
OK

(3)在目標Redis數據庫實例上檢查數據是否遷移成功。

127.0.0.1:6379> keys *
1) "hello"
127.0.0.1:6379> get hello
"world"

(4)在源Redis數據庫實例上再次執行migrate命令。

127.0.0.1:6379> migrate 192.168.79.12 6379 hello 0 1000
NOKEY

# 提示:migrate命令執行完成後,會刪除源Redis數據庫實例上鍵。
user avatar u_13482808 Avatar u_15844731 Avatar wuyongyin Avatar
Favorites 3 users favorite the story!
Favorites

Add a new Comments

Some HTML is okay.