如何使用 Python 的 MySQL 连接器监控数据库的性能指标(如查询时间、连接数等)?请设计一个简单的工具实现。

import mysql.connector
import time
from threading import Lock

class MySQLPerformanceMonitor:
    """
    一个简单的工具,用于监控 MySQL 数据库的性能指标,如查询时间和连接数。
    """

    def __init__(self, host, user, password, database):
        """
        初始化 MySQL 连接器并设置性能监控的基础参数。

        :param host: MySQL 主机地址
        :param user: MySQL 用户名
        :param password: MySQL 密码
        :param database: 数据库名称
        """
        self.host = host
        self.user = user
        self.password = password
        self.database = database
        self.connection = None
        self.query_times = []
        self.current_connections = 0
        self.lock = Lock()

    def connect(self):
        """
        连接到 MySQL 数据库。
        """
        self.connection = mysql.connector.connect(
            host=self.host,
            user=self.user,
            password=self.password,
            database=self.database
        )

    def execute_query(self, query):
        """
        执行 SQL 查询并记录查询时间。

        :param query: SQL 查询语句
        :return: 查询结果
        """
        if not self.connection:
            self.connect()

        cursor = self.connection.cursor()
        start_time = time.time()
        
        try:
            cursor.execute(query)
            result = cursor.fetchall()
            end_time = time.time()
            elapsed_time = end_time - start_time
            
            with self.lock:
                self.query_times.append(elapsed_time)
                print(f"查询耗时: {elapsed_time} 秒")
                self.current_connections = self.get_connection_count()
                print(f"当前连接数: {self.current_connections}")
            
            return result
        finally:
            cursor.close()

    def get_connection_count(self):
        """
        获取当前数据库的连接数。

        :return: 连接数
        """
        cursor = self.connection.cursor()
        cursor.execute("SHOW STATUS WHERE `variable_name` = 'Threads_connected'")
        result = cursor.fetchone()
        cursor.close()
        return int(result[1])

    def get_average_query_time(self):
        """
        计算所有查询的平均耗时。

        :return: 平均耗时(秒)
        """
        with self.lock:
            if not self.query_times:
                return 0
            return sum(self.query_times) / len(self.query_times)

    def close(self):
        """
        关闭数据库连接。
        """
        if self.connection:
            self.connection.close()
            self.connection = None

# 示例用法
if __name__ == "__main__":
    monitor = MySQLPerformanceMonitor(
        host="localhost",
        user="root",
        password="password",
        database="test_db"
    )

    try:
        # 执行查询
        result = monitor.execute_query("SELECT * FROM users WHERE id = 1")
        print(f"查询结果: {result}")
        
        # 获取平均查询时间
        avg_time = monitor.get_average_query_time()
        print(f"平均查询时间: {avg_time} 秒")
    finally:
        monitor.close()

功能说明

  1. 查询时间监控:每次执行查询时,工具会记录查询的耗时,并存储在列表中。可以通过 get_average_query_time 方法计算平均查询时间。
  2. 连接数监控:通过执行 SHOW STATUS 命令获取当前数据库的连接数,从而监控数据库的连接负载情况。
  3. 线程安全:使用 Lock 确保在多线程环境下对共享数据的访问是安全的。
  4. 资源管理:工具会在结束时关闭数据库连接,避免资源泄漏。

示例说明

  1. 初始化工具时,需要提供 MySQL 的主机地址、用户名、密码和数据库名称。
  2. 每次调用 execute_query 方法执行查询时,工具会自动记录查询时间并打印当前连接数。
  3. 可以通过 get_average_query_time 方法获取所有查询的平均耗时。

扩展

如果需要进一步监控其他性能指标(如 CPU 使用率、内存占用等),可以通过以下方式扩展:

  1. 调用 MySQL 的其他性能监控命令(如 SHOW GLOBAL STATUS 或 SHOW ENGINE INNODB STATUS)获取更详细的指标。
  2. 结合第三方库(如 psutil)监控服务器的系统资源使用情况。