Python進行Redis數據遷移
由于開發時的誤操作,導致redis數據損壞,所以需要進行redis的數據遷移,網上大佬的教程基本都是需要下載附加工具,亦或是需要一些復雜的操作,個人覺得麻煩還不如寫個腳本來的經濟實惠。
# -*- coding: utf-8 -*-
from redis import StrictRedis
"""
redis是用于操作Redis的第三方庫,StrictRedis是官方推薦的方法,而且Redis是它的子類,Redis能做到的StrictRedis基本都能做到
"""
def redis_data_migration():
"""
實現方法:遍歷源數據庫中的鍵值對,判斷類型,用對應的方法在目標數據庫中創建對應鍵值對
:return:
"""
'''
連接源數據庫與目標數據庫。而且你沒看錯,不需要password,我都不知道是咋校驗連接的
'''
# 連接參數需要根據個人情況修改
src_redis = StrictRedis(host='127.0.0.1', port=3306, db=8)
dst_redis = StrictRedis(host='127.0.0.1', port=3307, db=8)
print("Begin data migration:")
# 遍歷鍵值對
try:
for key in src_redis.keys():
# 鍵值對數據類型
key_type = str(src_redis.type(key))
# 字符串類型鍵值對
if key_type == 'string':
# 獲取源數據庫value
src_value = str(src_redis.get(key))
# 在目標數據庫中創建對應鍵值對
dst_redis.set(key, src_value)
# 插入到目標數據庫中的值
dst_value = dst_redis.get(key)
print('Migrate source {} type data{}={} to destination value {}'
.format(key_type, key, src_value, dst_value))
# 哈希字典類型鍵值對
elif key_type == 'hash':
# 獲取源數據庫value
src_value = src_redis.hgetall(key)
# 哈希類型鍵值對需要遍歷子鍵值對進行處理
for son_key in src_value:
son_key = str(son_key)
son_value = str(src_redis.hget(key, son_key))
# 在目標數據庫中創建對應鍵值對
dst_redis.hset(key, son_key, son_value)
# 插入到目標數據庫中的值
dst_value = dst_redis.hgetall(key)
print('Migrate source {} type data{}={} to destination value {}'
.format(key_type, key, src_value, dst_value))
# 列表類型鍵值對
elif key_type == 'list':
# 獲取源數據庫value,list類型可進行切片獲取對應鍵值
src_value = src_redis.lrange(key, 0, src_redis.llen(key))
for value in src_value:
# 在目標數據庫中創建對應鍵值對
dst_redis.rpush(key, str(value))
# 插入到目標數據庫中的值
dst_value = dst_redis.lrange(key, 0, src_redis.llen(key))
print('Migrate source {} type data{}={} to destination value {}'
.format(key_type, key, src_value, dst_value))
# 集合類型鍵值對
elif key_type == 'set':
# 獲取源數據庫value
src_value = src_redis.scard(key)
for value in src_redis.smembers(key):
# 在目標數據庫中插入對應鍵值對
dst_redis.sadd(key, str(value))
dst_value = dst_redis.scard(key)
print('Migrate source {} type data{}={} to destination value {}'
.format(key_type, key, src_value, dst_value))
# 有序集合類型鍵值對
elif key_type == 'zset':
# 獲取源數據庫value
src_value = src_redis.zcard(key)
# zset類型可以進行鍵值對范圍的選擇,這段代碼是選擇0-100行的鍵值對
for value in src_redis.zrange(key, 0, 100):
value = str(value)
score = int(src_redis.zscore(key, value))
# 在目標數據庫中插入對應鍵值對
dst_redis.zadd(key, score, value)
# 插入到目標數據庫中的值
dst_value = dst_redis.zcard(key)
print('Migrate source {} type data{}={} to destination value {}'
.format(key_type, key, src_value, dst_value))
except Exception as e:
print("Something wrong happened?。。。∣。O)")
print(e)
if __name__ == '__main__':
redis_data_migration()
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061
微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元

