search
HomeDatabaseMysql TutorialHow to implement python3 to implement concurrent access to horizontally split tables

The content of this article is about how to implement python3 to achieve concurrent access to horizontal split tables. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Scenario Description

Assume that a mysql table is horizontally split and distributed to multiple hosts. Each host has n split tables.
If you need to access these tables concurrently and get query results quickly, what should you do?
Here is a solution that uses python3's asyncio asynchronous io library and aiomysql asynchronous library to achieve this requirement.

Code Demonstration

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()

The above is the detailed content of How to implement python3 to implement concurrent access to horizontally split tables. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What Are the Limitations of Using Views in MySQL?What Are the Limitations of Using Views in MySQL?May 14, 2025 am 12:10 AM

MySQLviewshavelimitations:1)Theydon'tsupportallSQLoperations,restrictingdatamanipulationthroughviewswithjoinsorsubqueries.2)Theycanimpactperformance,especiallywithcomplexqueriesorlargedatasets.3)Viewsdon'tstoredata,potentiallyleadingtooutdatedinforma

Securing Your MySQL Database: Adding Users and Granting PrivilegesSecuring Your MySQL Database: Adding Users and Granting PrivilegesMay 14, 2025 am 12:09 AM

ProperusermanagementinMySQLiscrucialforenhancingsecurityandensuringefficientdatabaseoperation.1)UseCREATEUSERtoaddusers,specifyingconnectionsourcewith@'localhost'or@'%'.2)GrantspecificprivilegeswithGRANT,usingleastprivilegeprincipletominimizerisks.3)

What Factors Influence the Number of Triggers I Can Use in MySQL?What Factors Influence the Number of Triggers I Can Use in MySQL?May 14, 2025 am 12:08 AM

MySQLdoesn'timposeahardlimitontriggers,butpracticalfactorsdeterminetheireffectiveuse:1)Serverconfigurationimpactstriggermanagement;2)Complextriggersincreasesystemload;3)Largertablesslowtriggerperformance;4)Highconcurrencycancausetriggercontention;5)M

MySQL: Is it safe to store BLOB?MySQL: Is it safe to store BLOB?May 14, 2025 am 12:07 AM

Yes,it'ssafetostoreBLOBdatainMySQL,butconsiderthesefactors:1)StorageSpace:BLOBscanconsumesignificantspace,potentiallyincreasingcostsandslowingperformance.2)Performance:LargerrowsizesduetoBLOBsmayslowdownqueries.3)BackupandRecovery:Theseprocessescanbe

MySQL: Adding a user through a PHP web interfaceMySQL: Adding a user through a PHP web interfaceMay 14, 2025 am 12:04 AM

Adding MySQL users through the PHP web interface can use MySQLi extensions. The steps are as follows: 1. Connect to the MySQL database and use the MySQLi extension. 2. Create a user, use the CREATEUSER statement, and use the PASSWORD() function to encrypt the password. 3. Prevent SQL injection and use the mysqli_real_escape_string() function to process user input. 4. Assign permissions to new users and use the GRANT statement.

MySQL: BLOB and other no-sql storage, what are the differences?MySQL: BLOB and other no-sql storage, what are the differences?May 13, 2025 am 12:14 AM

MySQL'sBLOBissuitableforstoringbinarydatawithinarelationaldatabase,whileNoSQLoptionslikeMongoDB,Redis,andCassandraofferflexible,scalablesolutionsforunstructureddata.BLOBissimplerbutcanslowdownperformancewithlargedata;NoSQLprovidesbetterscalabilityand

MySQL Add User: Syntax, Options, and Security Best PracticesMySQL Add User: Syntax, Options, and Security Best PracticesMay 13, 2025 am 12:12 AM

ToaddauserinMySQL,use:CREATEUSER'username'@'host'IDENTIFIEDBY'password';Here'showtodoitsecurely:1)Choosethehostcarefullytocontrolaccess.2)SetresourcelimitswithoptionslikeMAX_QUERIES_PER_HOUR.3)Usestrong,uniquepasswords.4)EnforceSSL/TLSconnectionswith

MySQL: How to avoid String Data Types common mistakes?MySQL: How to avoid String Data Types common mistakes?May 13, 2025 am 12:09 AM

ToavoidcommonmistakeswithstringdatatypesinMySQL,understandstringtypenuances,choosetherighttype,andmanageencodingandcollationsettingseffectively.1)UseCHARforfixed-lengthstrings,VARCHARforvariable-length,andTEXT/BLOBforlargerdata.2)Setcorrectcharacters

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools