Copy related commands in Redis

Recently we have a case for copy keys stored in Redis, so I checked the commands supported by Redis.

The first is RENAME, not exactly the copy function, but is a simple way to rename the old key to new.

And here are the DUMP and RESTORE commands. DUMP serializes the value stored at key, while RESTORE deserializes the content, and creates the associated values.

A simple example is like this:

127.0.0.1:6379> FLUSHDB
OK
127.0.0.1:6379> HSET mykey foo f1 bar b1
(integer) 2
127.0.0.1:6379> DUMP mykey
"\r\x1d\x1d\x00\x00\x00\x18\x00\x00\x00\x04\x00\x00\x03foo\x05\x02f1\x04\x03bar\x05\x02b1\xff\t\x00#\xcf\xc4\xb5\xed6s\xa0"
127.0.0.1:6379> RESTORE newkey 0 "\r\x1d\x1d\x00\x00\x00\x18\x00\x00\x00\x04\x00\x00\x03foo\x05\x02f1\x04\x03bar\x05\x02b1\xff\t\x00#\xcf\xc4\xb5\xed6s\xa0"
OK
127.0.0.1:6379> HGETALL newkey
1) "foo"
2) "f1"
3) "bar"
4) "b1"
127.0.0.1:6379> HGETALL mykey
1) "foo"
2) "f1"
3) "bar"
4) "b1"
127.0.0.1:6379>

RESTORE also support several options for TTL and replacing the existed key.

There is also a command called MIGRATE which transfers one or more keys from one Redis instance to another. It simply executes a DUMP and DEL command in the source instance and a RESTORE in the target instance.