python3实现并发访问水平切分表的方法
发表于:2025-11-08 作者:千家信息网编辑
千家信息网最后更新 2025年11月08日,这篇文章给大家分享的是有关python3实现并发访问水平切分表的方法的内容。小编觉得挺实用的,因此分享给大家做个参考。一起跟随小编过来看看吧。场景说明假设有一个mysql表被水平切分,分散到多个hos
千家信息网最后更新 2025年11月08日python3实现并发访问水平切分表的方法
这篇文章给大家分享的是有关python3实现并发访问水平切分表的方法的内容。小编觉得挺实用的,因此分享给大家做个参考。一起跟随小编过来看看吧。
场景说明
假设有一个mysql表被水平切分,分散到多个host中,每个host拥有n个切分表。
如果需要并发去访问这些表,快速得到查询结果, 应该怎么做呢?
这里提供一种方案,利用python3的asyncio异步io库及aiomysql异步库去实现这个需求。
代码演示
import loggingimport randomimport asynciofrom aiomysql import create_pool# 假设mysql表分散在8个host, 每个host有16张子表TBLES = { "192.168.1.01": "table_000-015", # 000-015表示该ip下的表明从table_000一直连续到table_015 "192.168.1.02": "table_016-031", "192.168.1.03": "table_032-047", "192.168.1.04": "table_048-063", "192.168.1.05": "table_064-079", "192.168.1.06": "table_080-095", "192.168.1.07": "table_096-0111", "192.168.1.08": "table_112-0127",}USER = "xxx"PASSWD = "xxxx"# wrapper函数,用于捕捉异常def query_wrapper(func): async def wrapper(*args, **kwargs): try: await func(*args, **kwargs) except Exception as e: print(e) return wrapper # 实际的sql访问处理函数,通过aiomysql实现异步非阻塞请求@ query_wrapperasync def query_do_something(ip, db, table): async with create_pool(host=ip, db=db, user=USER, password=PASSWD) as pool: async with pool.get() as conn: async with conn.cursor() as cur: sql = ("select xxx from {} where xxxx") await cur.execute(sql.format(table)) res = await cur.fetchall() # then do something...# 生成sql访问队列, 队列的每个元素包含要对某个表进行访问的函数及参数def gen_tasks(): tasks = [] for ip, tbls in TBLES.items(): cols = re.split('_|-', tbls) tblpre = "_".join(cols[:-2]) min_num = int(cols[-2]) max_num = int(cols[-1]) for num in range(min_num, max_num+1): tasks.append( (query_do_something, ip, 'your_dbname', '{}_{}'.format(tblpre, num)) ) random.shuffle(tasks) return tasks# 按批量运行sql访问请求队列def run_tasks(tasks, batch_len): try: for idx in range(0, len(tasks), batch_len): batch_tasks = tasks[idx:idx+batch_len] logging.info("current batch, start_idx:%s len:%s" % (idx, len(batch_tasks))) for i in range(0, len(batch_tasks)): l = batch_tasks[i] batch_tasks[i] = asyncio.ensure_future( l[0](*l[1:]) ) loop.run_until_complete(asyncio.gather(*batch_tasks)) except Exception as e: logging.warn(e)# main方法, 通过asyncio实现函数异步调用def main(): loop = asyncio.get_event_loop() tasks = gen_tasks() batch_len = len(TBLES.keys()) * 5 # all up to you run_tasks(tasks, batch_len) loop.close()感谢各位的阅读!关于python3实现并发访问水平切分表的方法就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到吧!
函数
方法
水平
队列
内容
更多
不错
实用
代码
元素
参数
场景
多个
实际
文章
方案
看吧
知识
篇文章
结果
数据库的安全要保护哪些东西
数据库安全各自的含义是什么
生产安全数据库录入
数据库的安全性及管理
数据库安全策略包含哪些
海淀数据库安全审计系统
建立农村房屋安全信息数据库
易用的数据库客户端支持安全管理
连接数据库失败ssl安全错误
数据库的锁怎样保障安全
软件开发工商经验范围
天津电商软件开发制作
河北佳聘网络技术有限公司
青岛铭鼎网络技术有限公司
海通证券 服务器
网络技术在什么方面就业
南瑞的软件开发是外包人员吗
山东计算机网络技术本科学校
网络安全系列龙头股
idc机房服务器维护
数据库可以开发交互界面
ctf网络安全大赛存在吗
长沙软件开发定制怎么收费
徐州可视化智慧园区软件开发
常州营销服务管理软件开发
网络安全科技产品
安全牛数据库审计排名
老司机pvn服务器地址怎么填
保定智联软件开发公司
网络安全的智慧
软件开发目前现状
传输层中的网络技术与
数据库稀疏列
服务器里的文件怎么打印
小鸭五笔软件开发
crm软件开发团队
国外最新网络安全教育法
网络技术咨询师
举例说明事务对数据库的作用
网络安全周领导发言稿全文