神剑山庄资源网 Design By www.hcban.com
场景说明
假设有一个mysql表被水平切分,分散到多个host中,每个host拥有n个切分表。
如果需要并发去访问这些表,快速得到查询结果, 应该怎么做呢?
这里提供一种方案,利用python3的asyncio异步io库及aiomysql异步库去实现这个需求。
代码演示
import logging import random import 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,水平切分表
神剑山庄资源网 Design By www.hcban.com
神剑山庄资源网
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件!
如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
神剑山庄资源网 Design By www.hcban.com
暂无实例分析python3实现并发访问水平切分表的评论...
更新日志
2024年10月02日
2024年10月02日
- 孙悦.1996-伙伴【正大国际】【WAV+CUE】
- 纪钧瀚《钢琴阅读时光 雨中书店聆听轻音乐》[FLAC/分轨][399.62MB]
- 证声音乐图书馆《走向自然 疗心爵士乐》[320K/MP3][87.4MB]
- 证声音乐图书馆《走向自然 疗心爵士乐》[FLAC/分轨][184.94MB]
- 陈慧娴.2018-Priscilla-Ism演唱会3CD(2024环球红馆40复刻系列)【环球】【WAV+CUE】
- 郑秀文.1999-我应该得到(国)【华纳】【WAV+CUE】
- 陈家慧.2011-钢琴酒吧2CD【龙吟唱片】【WAV+CUE】
- 证声音乐图书馆《雨季 蓝调吉他 Rainy Blues》[320K/MP3][45.01MB]
- 证声音乐图书馆《雨季 蓝调吉他 Rainy Blues》[FLAC/分轨][109.13MB]
- 赞多《序章》[320K/MP3][45.54MB]
- 许巍.2004-每一刻都是崭新的【步升大风】【WAV+CUE】
- 群星.2024-四方馆影视原声带【韶愔音乐】【FLAC分轨】
- 陈雷.1997-安锁咧【金圆唱片】【WAV+CUE】
- 关淑怡.2013-MY.FAVORITE.SK.3CD【环球】【WAV+CUE】
- Sweety.2006-花言乔语【丰华】【WAV+CUE】