首頁 >資料庫 >mysql教程 >如何實現python3實現並發存取水平切分錶

如何實現python3實現並發存取水平切分錶

坏嘻嘻
坏嘻嘻原創
2018-09-15 10:25:091696瀏覽

這篇文章帶給大家的內容是關於如何實現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實現並發存取水平切分錶的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn