旗下导航:搜·么
当前位置:网站首页 > MySQL教程 > 正文

怎样完成python3完成并发接见程度切分表【MySQL教程】,mysql,python

作者:搜教程发布时间:2019-12-01分类:MySQL教程浏览:47评论:0


导读:本篇文章给人人带来的内容是关于怎样完成python3完成并发接见程度切分表,有肯定的参考价值,有须要的朋侪能够参考一下,愿望对你有所协助。场景申明假定有一个mysql...

本篇文章给人人带来的内容是关于怎样完成python3完成并发接见程度切分表,有肯定的参考价值,有须要的朋侪能够参考一下,愿望对你有所协助。

场景申明

假定有一个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完成并发接见程度切分表的细致内容,更多请关注ki4网别的相干文章!

标签:mysqlpython


欢迎 发表评论: