Python3操作redis百万级数据迁移,单机到单机,集群到集群

embedded/2024/9/23 9:02:48/

Python3操作redis大量数据迁移 脚本

  • 背景
  • 使用前
  • 使用注意事项
  • 脚本
  • 总结

背景

之前写过一个用python迁移redis的脚本,但是对于小批量的数据、单节点的,还可以用。对于大量数据,集群模式的就不太适合了。所以写了下面的脚本,而且做了一定的优化,使用的pipeline和多线程,保证了迁移数据的速度,本人测试,大概2分钟复制了110万键值对的数据,差不多是每秒一万键值对的复制速度。

使用前

注意:

  1. 用的是Python3环境,Python2的大概需要改一下print输出
  2. 安装相关的模块
pip install redis rediscluster
  1. 可以在windows、linux环境下使用,注意修改里面的一些设置

使用注意事项

下面是一些需要注意的:

  1. 下面的脚本,如果redis数据超过500万键值对,很可能会有瓶颈,因为是一次性取的redis的所有键组成列表,列表很大,大概率会有阻塞。这样就不建议这种迁移方式了
  2. 下面的脚本,是建立在新的redis实例是空数据,或者说没有与原redis实例键值重复的情况下,要不然会重写。
  3. 下面的脚本,是迁移了所有键值对,没有做一些键的匹配,不过改起来不复杂
  4. 下面的脚本,多线程和批量提交的参数,如有必要可以改一下,对比测试。包括一些redis实例的参数配置也一样,如有必要可以改。
  5. 下面的脚本,单机到集群等各种迁移模式,要根据实际情况进行修改。
  6. 这个脚本,没办法实现实时复制,如果原redis数据库一直有增量数据,而且比较大,最好用其他方式迁移。因为脚本读取的redis Key值列表,只是那一个时间的,新库老库数据会有几分钟的差异。如果是把redis当做持久化库而不是缓存库的情况,也不适合。

暂时就这些了。

脚本

内容如下,根据实际情况进行调整

python3">#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 2024/4/24from datetime import datetime
import time
import threading
import redis
from rediscluster import RedisClusterdef split_list(big_list, num=1):"""原来是[1,2,3,4,5,6]的列表,拆分成[[1,2], [3,4], [5,6]]小列表,主要是为了多线程:param big_list: 大列表:param num: 拆分多少个列表,这个主要对应后面的线程数,或者说redis的连接数,不能设置的太大,否则会报错Too many connections:return: 新的列表"""list_len = len(big_list)new_list = []if list_len > num:if list_len % num == 0:small_list_len = list_len // numelse:small_list_len = list_len // num + 1start = 0for i in range(num):# print(i)new_list.append(big_list[start: start + small_list_len])start += small_list_lenelse:new_list.append(big_list)return new_listdef redis_get_set(redis_source, redis_target, redis_list,  batch_size=100):"""读取redis“键”列表,获取Key/Value值,写入到新的redis:param redis_source: 原redis实例:param redis_target: 新redis实例:param redis_list: 要迁移的redis Key值列表:param batch_size: 使用pipeline写入新的redis实例,提高写入效率:return:"""count = 0with redis_target.pipeline() as pipe:for k in redis_list:data_type = redis_source.type(k)# 判断key值数据类型,分别处理,没有stream数据类型的处理,后面有必要再添加if data_type == 'string':v = redis_source.get(k)redis_target.set(k, v)elif data_type == 'list':v = redis_source.lrange(k, 0, -1)redis_target.lpush(k, *v)elif data_type == 'set':v = redis_source.smembers(k)redis_target.sadd(k, *v)elif data_type == 'hash':fields = redis_source.hgetall(k)pipe.hset(k, mapping=fields)elif data_type == 'zset':v = redis_source.zrange(k, 0, -1, withscores=True)# 需要将元组数据转化为字典数据redis_target.zadd(k, dict(v))else:print('not known type')count += 1# 如果数据量较大,循环batch_size次数后提交一次if count % batch_size == 0:print(f'\n当前时间:{datetime.now()},进程:{threading.current_thread()},已完成{count}对读写操作')pipe.execute()pipe.reset()# 最后再提交一次pipelinepipe.execute()pipe.reset()print(f'\n当前时间:{datetime.now()},进程:{threading.current_thread()},已完成所有读写操作!')def redis_copy(redis_source, redis_target, thread_num=5, batch_size=100):"""将原始redis的Key值大列表进行拆分,然后拆分后的列表进行多线程处理:param redis_source: 原redis实例:param redis_target: 新redis实例:param thread_num: 线程数,将大列表拆分为几个小列表,这个数不要太大,一般10个就行,不然程序会报错:param batch_size::return:"""# 检查两个redis是否可用try:redis_source.ping()redis_target.ping()print("Redis节点可连接")except Exception as e:print(f"连接Redis失败: {e}")redis_target = None# 线程列表threads = []if redis_target:new_list = split_list(redis_source.keys('*'), thread_num)for data in new_list:t = threading.Thread(target=redis_get_set, args=(redis_source, redis_target, data, batch_size))threads.append(t)t.start()for t in threads:t.join()print("所有线程执行完毕")def single_to_single(thread_num, batch_size):"""单节点迁移到单节点"""# 原始redis,单节点source_pool = redis.ConnectionPool(host='192.168.10.1',port=6379,db=0,password='123456',encoding='utf-8',decode_responses=True,socket_timeout=10,max_connections=100)redis_source = redis.Redis(connection_pool=source_pool)# 目标redis,单节点target_pool = redis.ConnectionPool(host='192.168.10.2',port=6369,db=0,password='123456',encoding='utf-8',decode_responses=True,socket_timeout=10,max_connections=100)redis_target = redis.Redis(connection_pool=target_pool)redis_copy(redis_source, redis_target, thread_num=10, batch_size=10000)def single_to_cluster(thread_num, batch_size):"""单节点迁移到单节点"""# 原始redis,单节点source_pool = redis.ConnectionPool(host='192.168.10.1',port=6379,db=0,password='123456',encoding='utf-8',decode_responses=True,socket_timeout=10,max_connections=100)redis_source = redis.Redis(connection_pool=source_pool)# 目标redis,集群target_node_list = [{"host": "192.168.11.1", "port": "6379"},{"host": "192.168.11.2", "port": "6379"},{"host": "192.168.11.3", "port": "6379"},{"host": "192.168.11.4", "port": "6379"},{"host": "192.168.11.5", "port": "6379"},{"host": "192.168.11.6", "port": "6379"},]# 创建RedisCluster的实例# decode_responses设置为True会自动将响应数据解码为utf-8编码的字符串redis_cluster_target = RedisCluster(startup_nodes=target_node_list,decode_responses=True,password='123456')redis_copy(redis_source, redis_cluster_target, thread_num=10, batch_size=10000)def cluster_to_single(thread_num, batch_size):"""集群迁移到集群"""# 原始redis,集群source_node_list = [{"host": "192.168.0.1", "port": "6379"},{"host": "192.168.0.2", "port": "6379"},{"host": "192.168.0.3", "port": "6379"},{"host": "192.168.0.4", "port": "6379"},{"host": "192.168.0.5", "port": "6379"},{"host": "192.168.0.6", "port": "6379"},]# 创建RedisCluster的实例# decode_responses设置为True会自动将响应数据解码为utf-8编码的字符串redis_cluster_source = RedisCluster(startup_nodes=source_node_list,decode_responses=True,password='123456')# 目标redis,单节点target_pool = redis.ConnectionPool(host='192.168.10.2',port=6369,db=0,password='123456',encoding='utf-8',decode_responses=True,socket_timeout=10,max_connections=100)redis_target = redis.Redis(connection_pool=target_pool)redis_copy(redis_cluster_source, redis_target, thread_num=10, batch_size=10000)def cluster_to_cluster(thread_num, batch_size):"""集群迁移到集群"""# 原始redis,集群source_node_list = [{"host": "192.168.0.1", "port": "6379"},{"host": "192.168.0.2", "port": "6379"},{"host": "192.168.0.3", "port": "6379"},{"host": "192.168.0.4", "port": "6379"},{"host": "192.168.0.5", "port": "6379"},{"host": "192.168.0.6", "port": "6379"},]# 创建RedisCluster的实例# decode_responses设置为True会自动将响应数据解码为utf-8编码的字符串redis_cluster_source = RedisCluster(startup_nodes=source_node_list,decode_responses=True,password='123456')# 目标redis,集群target_node_list = [{"host": "192.168.11.1", "port": "6379"},{"host": "192.168.11.2", "port": "6379"},{"host": "192.168.11.3", "port": "6379"},{"host": "192.168.11.4", "port": "6379"},{"host": "192.168.11.5", "port": "6379"},{"host": "192.168.11.6", "port": "6379"},]# 创建RedisCluster的实例# decode_responses设置为True会自动将响应数据解码为utf-8编码的字符串redis_cluster_target = RedisCluster(startup_nodes=target_node_list,decode_responses=True,password='123456')redis_copy(redis_cluster_source, redis_cluster_target, thread_num=10, batch_size=10000)if __name__ == '__main__':# 性能与效率控制# 线程数thread_num = 10# 写入批量提交数batch_size = 10000start_time = time.perf_counter()# 单节点迁移到单节点single_to_single(thread_num, batch_size)# 单节点迁移到集群# single_to_cluster(thread_num, batch_size)# 集群迁移到单节点# cluster_to_single(thread_num, batch_size)# 集群迁移到集群# cluster_to_cluster(thread_num, batch_size)end_time = time.perf_counter()# 计算执行时间execution_time = end_time - start_timeprint(f"代码执行时间: {execution_time} 秒")

总结

上面的代码,为了优化性能,改了好几次。刚开始的时候,50万键值对数据(5个数据类型各10万左右),迁移复制大概需要300s-400s左右,平均每秒钟大约复制1300-1700的键值对,经过多次优化,平均每秒钟大约复制9000的键值对,提升了6-7倍左右。

优化思路:

  1. 使用pipeline,批量提交键值对到新的库
  2. 在数据量比较大的情况下,原redis的键整体取出后,是一个比较大的列表,先将这个大列表拆分为较为平均的几个小列表,然后使用多线程分别对小列表数据读写,可能大大提高读写效率。但是线程数也没必要设置太高,一个是redis连接数有限制,还有一个是我试了一下,比如从10提升到20,读写速度提升的不是太明显。

其它思考:
1 还能进行哪些优化呢?我看有些商业软件能做到每秒钟10万级别KV的复制,想不出来怎么做的。


http://www.ppmy.cn/embedded/14357.html

相关文章

ChatGPT实战100例 - (18) 用事件风暴玩转DDD

文章目录 ChatGPT实战100例 - (18) 用事件风暴玩转DDD一、标准流程二、定义目标和范围三、准备工具和环境四、列举业务事件五、 组织和排序事件六、确定聚合并引入命令七、明确界限上下文八、识别领域事件和领域服务九、验证和修正模型十、生成并验证软件设计十一、总结 ChatGP…

探索visionOS基础知识:创建应用程序图标

每当您使用不同的 Apple 平台时,您都会注意到必须学习如何为其设计本机应用程序图标。无论是 iOS、macOS 还是 tvOS,每个平台都有适合该特定平台的独特规范。 VisionOS 要求创建美观、三维、独特的应用程序图标,使主视图上感觉熟悉且逼真。 对于与 VisionOS 兼容的现有 …

NXP恩智浦 S32G电源管理芯片 VR5510 安全概念 Safety Concept (万字长文详解,配21张彩图)

NXP恩智浦 S32G电源管理芯片 VR5510 安全概念 Safety Concept (万字长文详解,配21张彩图) 1. 简介 本应用笔记描述了与S32G处理器和VR5510 PMIC相关的安全概念。该文档涵盖了S32G和VR5510的安全功能以及它们如何相互作用,以确保对ASIL D安全完整性级别…

在 vue3 中使用高德地图

前言:定位地图位置所需要的经纬度,可以通过 拾取坐标 获取。 一:快速上手 1. 安装依赖 npm install amap/amap-jsapi-loader # or pnpm add amap/amap-jsapi-loader # or yarn add amap/amap-jsapi-loader 2. 创建组件 src/components/Ma…

黑马微服务课程2

课程地址:2024最新SpringCloud微服务开发与实战,java黑马商城项目微服务实战开发(涵盖MybatisPlus、Docker、MQ、ES、Redis高级等)_哔哩哔哩_bilibili 课程名称:2024最新SpringCloud微服务开发与实战,java…

Web前端开发之HTML_1

第一个前端程序VS Code安装VS Code 快捷键 1. 第一个前端程序 使用记事本&#xff0c;新建一个文本文档&#xff0c;重命名为Welcome.html&#xff0c;如下图&#xff1a; 用记事本打开文档&#xff0c;内容输入如下&#xff1a; <html> <head> <t…

Node+Vue3+mysql+ant design实现前后端分离——表格的添加、修改和删除

在上一篇文章中,我们分享了如何运用NodeJS、Vue、MySQL以及其他技术来实现后台管理系统中的表格查询功能。今天,我们将继续探讨另外三个重要的功能实现原则。这些原则在构建后台管理系统时至关重要,同时还有导入和导出这两种功能也必不可少。关于导入和导出功能,我们会在下…

vue2使用elementUI报错

在vue2中安装elementUI&#xff0c;在全局引入elementUIcss的时候报错&#xff0c;解决办法是在根目录下新建一个名称为postcss.config.js文件 文件中放入代码&#xff1a; module.exports {plugins: {autoprefixer: {}} }重启项目就可以正常运行&#xff0c;elementUI的样式…