本方法通过编写Shell脚本,逐个获取key,根据KEY不同的类型逐个KEY迁移,速度慢,量大的情况下不推荐使用
#!/bin/bash
#地址
host='127.0.0.1'
#源端口
src_port=7000
#目标端口
dest_port=8000
#计数器,统计迁移了多少KEY,末尾打印
cnt=0
#遍历获取所有KEY
for k in `redis-cli -h $host -p $src_port keys "*"`
do
data_type=`redis-cli -h $host -p $src_port type $k`
#逐个判断KEY的类型后,将KEY读出来,写入到目标Redis
case $data_type in
'string')
v=`redis-cli -h $host -p $src_port get $k`
redis-cli -h $host -p $dest_port set $k $v
;;
'list')
values=`redis-cli -h $host -p $src_port lrange $k 0 -1`
redis-cli -h $host -p $dest_port lpush $k $values
;;
'set')
values=`redis-cli -h $host -p $src_port smembers $k`
redis-cli -h $host -p $dest_port sadd $k $values
;;
'hash')
for key in `redis-cli -h $host -p $src_port hkeys $k`
do
hvalue=`redis-cli -h $host -p $src_port hget $k $key`
redis-cli -h $host -p $dest_port hset $k $key $hvalue
done
;;
*)
echo "not known type"
;;
esac
let cnt++
done
#打印迁移的KEY
echo $cnt
执行情况
bak]# sh m.sh
OK
(integer) 1
(integer) 1
(integer) 1
OK
OK
OK
(integer) 3
OK
OK
(integer) 1
OK
(integer) 5
OK
OK
(integer) 1
(integer) 1
OK
15
结果验证
bak]# redis-cli -h 127.0.0.1 -p 8000 keys '*'
1) "k2"
2) "sname"
3) "k10"
4) "k4"
5) "hclass1"
6) "k8"
7) "k9"
8) "hclass2"
9) "k3"
10) "k6"
11) "lname"
12) "hclass3"
13) "k1"
14) "k7"
15) "k5"
注: 参考网上的python脚本,由于我执行python代码的时候报错,手动改为shell脚本;
感兴趣可以参考:
#coding=utf-8
import redis
redis_from = redis.StrictRedis(host='127.0.0.1', port=6379, db=10)
redis_to = redis.StrictRedis(host='127.0.0.1', port=6379, db=0)
if __name__ == '__main__':
cnt = 0
for k in redis_from.keys():
data_type = redis_from.type(k)
if data_type == 'string':
v = redis_from.get(k)
redis_to.set(k, v)
elif data_type == 'list':
values = redis_from.lrange(k, 0, -1)
redis_to.lpush(k, values)
elif data_type == 'set':
values = redis_from.smembers(k)
redis_to.sadd(k, values)
elif data_type == 'hash':
keys = redis_from.hkeys(k)
for key in keys:
value = redis_from.hget(k, key)
redis_to.hset(k, key, value)
else:
print 'not known type'
cnt = cnt + 1
print 'total', cnt