Redis Move 命令

Redis key(鍵)

Redis MOVE 命令用於將當前資料庫的 key 移動到給定的資料庫 db 當中。

語法

redis Move 命令基本語法如下:

redis 127.0.0.1:6379> MOVE KEY_NAME DESTINATION_DATABASE

可用版本

>= 1.0.0

返回值

移動成功返回 1 ,失敗則返回 0 。

實例

# key 存在於當前資料庫

redis> SELECT 0                             # redis默認使用資料庫 0,為了清晰起見,這裏再顯式指定一次。

OK

redis> SET song "secret base - Zone"
OK

redis> MOVE song 1                          # 將 song 移動到資料庫 1
(integer) 1

redis> EXISTS song                          # song 已經被移走

(integer) 0

redis> SELECT 1                             # 使用資料庫 1
OK

redis:1> EXISTS song                        # 證實 song 被移到了資料庫 1 (注意命令提示符變成了"redis:1",表明正在使用資料庫 1)
(integer) 1


# 當 key 不存在的時候


redis:1> EXISTS fake_key
(integer) 0

redis:1> MOVE fake_key 0                    # 試圖從資料庫 1 移動一個不存在的 key 到資料庫 0,失敗

(integer) 0

redis:1> select 0                           # 使用資料庫0
OK

redis> EXISTS fake_key                      # 證實 fake_key 不存在

(integer) 0


# 當源資料庫和目標資料庫有相同的 key 時


redis> SELECT 0                             # 使用資料庫0
OK
redis> SET favorite_fruit "banana"
OK

redis> SELECT 1                             # 使用資料庫1
OK
redis:1> SET favorite_fruit "apple"
OK

redis:1> SELECT 0                           # 使用資料庫0,並試圖將 favorite_fruit 移動到資料庫 1
OK

redis> MOVE favorite_fruit 1                # 因為兩個數據庫有相同的 key,MOVE 失敗
(integer) 0

redis> GET favorite_fruit                   # 資料庫 0 的 favorite_fruit 沒變
"banana"

redis> SELECT 1
OK

redis:1> GET favorite_fruit                 # 資料庫 1 的 favorite_fruit 也是
"apple"

Redis key(鍵)