架构师_程序员_码农网

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 9814|回复: 2

[资料] python3实现并发访问水平切分表

[复制链接]
发表于 2017-11-29 21:15:55 | 显示全部楼层 |阅读模式
场景说明

假设有一个mysql表被水平切分,分散到多个host中,每个host拥有n个切分表。
如果需要并发去访问这些表,快速得到查询结果, 应该怎么做呢?
这里提供一种方案,利用python3的asyncio异步io库及aiomysql异步库去实现这个需求。

代码演示

import logging
import random
import asyncio
from 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_wrapper
async 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
                batch_tasks = 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()





上一篇:怎么充值啊。
下一篇:WebAPI 自定义返回数据格式
码农网,只发表在实践过程中,遇到的技术难题,不误导他人。
发表于 2017-11-30 09:03:52 | 显示全部楼层
不错  分库分表  优化数据库
码农网,只发表在实践过程中,遇到的技术难题,不误导他人。
发表于 2018-4-4 15:20:12 | 显示全部楼层
赞哦
码农网,只发表在实践过程中,遇到的技术难题,不误导他人。
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则

免责声明:
码农网所发布的一切软件、编程资料或者文章仅限用于学习和研究目的;不得将上述内容用于商业或者非法用途,否则,一切后果请用户自负。本站信息来自网络,版权争议与本站无关。您必须在下载后的24个小时之内,从您的电脑中彻底删除上述内容。如果您喜欢该程序,请支持正版软件,购买注册,得到更好的正版服务。如有侵权请邮件与我们联系处理。

Mail To:help@itsvse.com

QQ|手机版|小黑屋|架构师 ( 鲁ICP备14021824号-2 )|网站地图

GMT+8, 2024-4-27 09:59

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表