由于开发时的误操作,导致Redis数据损坏,所以需要进行Redis的数据迁移,转了一圈网上的教程基本都是需要下载附加工具,或是需要一些复杂的操作,为了提升效率,还是自己写了个脚本。
- Python版本代码
# -*- coding: utf-8 -*-
from redis import StrictRedis
def get_redis_conn(config_dict):
"""
生成需要迁移数据的redis配置
:return:
"""
try:
redis_conn = StrictRedis(
host=config_dict.get('host'),
port=config_dict.get('port'),
db=config_dict.get('db'),
password=config_dict.get('password')
)
print("Connect redis {} succeed".format(config_dict.get('host')))
return redis_conn
except Exception as e:
print("Something wrong happened {}".format(e))
def redis_data_migration(src_cfg_dict, dst_cfg_dict):
"""
实现方法:遍历源数据库中的键值对,判断类型,用对应的方法在目标数据库中创建对应键值对
:return:
"""
# 连接参数需要根据个人情况修改
src_conn = get_redis_conn(src_cfg_dict)
dst_conn = get_redis_conn(dst_cfg_dict)
src_value = None
print("Begin data migration from {} to {} ...".format(src_cfg_dict.get('host'), dst_cfg_dict.get('host')))
cursor = 0
count = 10000
# 遍历键值对
try:
while 1:
cursor, keys = src_conn.scan(cursor=cursor, count=count)
for key in keys:
# 键值对数据类型
key_type = str(src_conn.type(key).decode('utf-8'))
print("Cur key {} type {}".format(key.decode('utf-8'), key_type), end=" ")
# 字符串类型键值对
if key_type == 'string':
# 获取源数据库value
src_value = str(src_conn.get(key).decode('utf-8'))
# 获取过期时间
ex = src_conn.ttl(key)
if -1 == ex:
ex = None
# 在目标数据库中创建对应键值对
dst_conn.set(key