使用 Python 线程池和线程队列实现数据库表数据统计对比

本代码演示如何使用 Python 线程池和线程队列实现对源、目标数据库中所有表进行 select count(1) 操作,统计表数据并进行对比,判断行数是否一致。

功能特点:

  • 自定义最大并发数,控制同时执行的数据统计任务数量。
  • 实时输出总线程数、完成线程数、未完成线程数。
  • 对源、目标数据库进行数据统计时也使用多线程,提高效率。
  • 确保多线程环境下数据不会混乱。

代码示例:

import csv
import threading
import queue
import time
import pymysql
from concurrent.futures import ThreadPoolExecutor

# 定义最大并发数
MAX_CONCURRENT = 5

# 定义数据库连接信息文件路径
DATABASE_INFO_FILE = 'database_info.csv'

# 定义线程队列
thread_queue = queue.Queue()

# 定义线程池执行器
thread_pool_executor = ThreadPoolExecutor(max_workers=MAX_CONCURRENT)

# 定义锁,用于保证数据统计的线程安全
lock = threading.Lock()

# 定义全局变量,用于统计总线程数、完成线程数和未完成线程数
total_threads = 0
completed_threads = 0
uncompleted_threads = 0

# 定义输出日志函数
def log_info(message):
    print(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] {message}")

# 定义数据库连接函数
def connect_to_database(database_info):
    host = database_info['host']
    port = database_info['port']
    user = database_info['user']
    password = database_info['password']
    database = database_info['database']

    try:
        conn = pymysql.connect(host=host, port=int(port), user=user, password=password, database=database)
        return conn
    except Exception as e:
        log_info(f"Failed to connect to database {database}: {str(e)}")
        return None

# 定义数据统计函数
def count_data(database_info):
    global completed_threads, uncompleted_threads

    source_database = database_info['source']
    target_database = database_info['target']

    source_conn = connect_to_database(source_database)
    target_conn = connect_to_database(target_database)

    if source_conn and target_conn:
        source_cursor = source_conn.cursor()
        target_cursor = target_conn.cursor()

        try:
            source_cursor.execute("SHOW TABLES")
            source_tables = [table[0] for table in source_cursor.fetchall()]

            target_cursor.execute("SHOW TABLES")
            target_tables = [table[0] for table in target_cursor.fetchall()]

            for table in source_tables:
                if table in target_tables:
                    source_cursor.execute(f"SELECT COUNT(1) FROM {table}")
                    source_count = source_cursor.fetchone()[0]

                    target_cursor.execute(f"SELECT COUNT(1) FROM {table}")
                    target_count = target_cursor.fetchone()[0]

                    with lock:
                        log_info(f"{source_database['database']}::{table}: {source_count} rows")
                        log_info(f"{target_database['database']}::{table}: {target_count} rows")

                        if source_count == target_count:
                            log_info(f"The row count of {source_database['database']}::{table} is consistent with {target_database['database']}::{table}")
                        else:
                            log_info(f"The row count of {source_database['database']}::{table} is inconsistent with {target_database['database']}::{table}")

            source_cursor.close()
            target_cursor.close()

        except Exception as e:
            log_info(f"Error occurred during data count: {str(e)}")

        finally:
            source_conn.close()
            target_conn.close()

    with lock:
        completed_threads += 1
        uncompleted_threads -= 1

# 定义线程函数
def worker():
    while True:
        database_info = thread_queue.get()
        if database_info is None:
            break
        count_data(database_info)

# 读取数据库连接信息
database_infos = []
with open(DATABASE_INFO_FILE, 'r') as file:
    reader = csv.DictReader(file)
    for row in reader:
        database_infos.append({
            'source': {
                'host': row['source_host'],
                'port': row['source_port'],
                'user': row['source_user'],
                'password': row['source_password'],
                'database': row['source_database']
            },
            'target': {
                'host': row['target_host'],
                'port': row['target_port'],
                'user': row['target_user'],
                'password': row['target_password'],
                'database': row['target_database']
            }
        })

# 初始化线程队列
for database_info in database_infos:
    thread_queue.put(database_info)

# 计算总线程数
total_threads = thread_queue.qsize()

# 初始化未完成线程数
uncompleted_threads = total_threads

# 创建线程池
threads = []
for _ in range(MAX_CONCURRENT):
    thread = threading.Thread(target=worker)
    threads.append(thread)
    thread.start()

# 输出总线程数、完成线程数、未完成线程数
while uncompleted_threads > 0:
    log_info(f"Total threads: {total_threads}, Completed threads: {completed_threads}, Uncompleted threads: {uncompleted_threads}")
    time.sleep(1)

# 等待所有线程执行完毕
for _ in range(MAX_CONCURRENT):
    thread_queue.put(None)

for thread in threads:
    thread.join()

log_info("All threads completed.")

使用说明:

  1. 确保已安装 pymysql 库:pip install pymysql
  2. 创建 database_info.csv 文件,并按照以下格式添加数据库连接信息:
source_host,source_port,source_user,source_password,source_database,target_host,target_port,target_user,target_password,target_database
source_host1,source_port1,source_user1,source_password1,source_database1,target_host1,target_port1,target_user1,target_password1,target_database1
source_host2,source_port2,source_user2,source_password2,source_database2,target_host2,target_port2,target_user2,target_password2,target_database2
...
  1. 修改 MAX_CONCURRENT 和 DATABASE_INFO_FILE 变量,根据实际情况设置最大并发数和数据库连接信息文件路径。
  2. 运行代码,即可看到数据统计和对比结果。

注意事项:

  • 确保数据库连接信息正确无误。
  • 使用多线程时,应注意数据安全和线程同步问题。
  • 可以根据实际情况调整代码中的参数和逻辑。

代码解析:

  1. 导入必要的库:csv 用于读取 csv 文件,threading 用于创建线程,queue 用于创建线程队列,time 用于控制时间间隔,pymysql 用于连接数据库,concurrent.futures 用于创建线程池。
  2. 定义全局变量:
    • MAX_CONCURRENT:最大并发数。
    • DATABASE_INFO_FILE:数据库连接信息文件路径。
    • thread_queue:线程队列,用于存放数据库连接信息。
    • thread_pool_executor:线程池执行器,用于管理线程池。
    • lock:锁,用于保证数据统计的线程安全。
    • total_threads:总线程数。
    • completed_threads:完成线程数。
    • uncompleted_threads:未完成线程数。
  3. 定义输出日志函数:log_info 函数用于输出日志信息,包含时间戳和消息内容。
  4. 定义数据库连接函数:connect_to_database 函数用于连接数据库,根据提供的数据库连接信息建立连接,并返回连接对象。
  5. 定义数据统计函数:count_data 函数用于统计表数据并进行对比,包括以下步骤:
    • 连接源数据库和目标数据库。
    • 获取源数据库和目标数据库的所有表名。
    • 遍历源数据库中的表,如果目标数据库中存在相同表名,则分别执行 SELECT COUNT(1) FROM table 获取表数据量。
    • 输出源数据库和目标数据库中每个表的行数。
    • 判断行数是否一致,并输出对比结果。
    • 关闭数据库连接。
  6. 定义线程函数:worker 函数是线程执行的函数,从线程队列中获取数据库连接信息,并调用 count_data 函数进行数据统计和对比。
  7. 读取数据库连接信息:从 database_info.csv 文件中读取数据库连接信息,并存储在 database_infos 列表中。
  8. 初始化线程队列:将 database_infos 列表中的数据库连接信息添加到线程队列中。
  9. 计算总线程数:获取线程队列的大小,即总线程数。
  10. 初始化未完成线程数:将未完成线程数设置为总线程数。
  11. 创建线程池:根据 MAX_CONCURRENT 创建线程池,并启动每个线程。
  12. 输出线程状态:循环输出总线程数、完成线程数、未完成线程数,每隔 1 秒输出一次。
  13. 等待所有线程执行完毕:将 None 添加到线程队列中,通知所有线程停止执行,并等待所有线程执行完毕。
  14. 输出日志:输出所有线程执行完毕的日志信息。

总结

本代码利用线程池和线程队列,实现了数据库表数据统计对比的功能,可以有效地提高数据统计效率,并实时输出线程状态和对比结果。您可以根据实际需求修改代码中的参数和逻辑,以适应不同的应用场景。

Python 线程池和线程队列实现数据库表数据统计对比