#!/usr/bin/env python3 """ 数据库连接池管理模块演示脚本 展示数据库连接池的核心功能。 """ import time import threading from core.connection_pool import ConnectionPool, pool_manager def demo_basic_operations(): """演示基本操作""" print("\n" + "="*60) print("演示1: 连接池基本操作") print("="*60) pool = ConnectionPool( min_connections=2, max_connections=5, host="localhost", port=3306, database="test_db", user="test_user", password="test_pass" ) # 获取连接 conn = pool.get_connection() print(f"✅ 获取连接成功: {conn.id}") # 执行查询 result = conn.execute("SELECT 1") print(f"✅ 执行查询: {result}") # 释放连接 pool.release_connection(conn) print("✅ 释放连接成功") # 关闭连接池 pool.close() print("✅ 连接池关闭成功") def demo_capacity_limit(): """演示容量限制""" print("\n" + "="*60) print("演示2: 连接池容量限制") print("="*60) pool = ConnectionPool( min_connections=1, max_connections=3, host="localhost", port=3306, database="test_db", user="test_user", password="test_pass" ) # 获取3个连接 conn1 = pool.get_connection() conn2 = pool.get_connection() conn3 = pool.get_connection() print("✅ 获取3个连接") # 尝试获取第4个连接(应该超时) print("⏱️ 尝试获取第4个连接(应该超时)...") try: conn4 = pool.get_connection(timeout=1) print(f"⚠️ 获取到第4个连接: {conn4.id}") except Exception as e: print(f"✅ 第4个连接获取超时: {str(e)}") # 释放一个连接 pool.release_connection(conn1) print("✅ 释放连接1") # 现在可以获取新连接 conn4 = pool.get_connection() print(f"✅ 释放后成功获取新连接: {conn4.id}") # 清理 pool.release_connection(conn2) pool.release_connection(conn3) pool.release_connection(conn4) pool.close() def demo_statistics(): """演示统计信息""" print("\n" + "="*60) print("演示3: 连接池统计信息") print("="*60) pool = ConnectionPool( min_connections=2, max_connections=5, host="localhost", port=3306, database="test_db", user="test_user", password="test_pass" ) # 获取初始统计 stats = pool.get_stats() print(f"✅ 初始统计:") print(f" 总连接数: {stats['total_connections']}") print(f" 空闲连接: {stats['idle_connections']}") print(f" 活跃连接: {stats['active_connections']}") # 获取连接 conn = pool.get_connection() stats_after_get = pool.get_stats() print(f"\n✅ 获取连接后统计:") print(f" 空闲连接: {stats_after_get['idle_connections']}") print(f" 活跃连接: {stats_after_get['active_connections']}") print(f" 总获取次数: {stats_after_get['total_get_count']}") # 释放连接 pool.release_connection(conn) stats_after_release = pool.get_stats() print(f"\n✅ 释放连接后统计:") print(f" 空闲连接: {stats_after_release['idle_connections']}") print(f" 活跃连接: {stats_after_release['active_connections']}") print(f" 总释放次数: {stats_after_release['total_release_count']}") pool.close() def demo_health_check(): """演示健康检查""" print("\n" + "="*60) print("演示4: 连接池健康检查") print("="*60) pool = ConnectionPool( min_connections=2, max_connections=5, host="localhost", port=3306, database="test_db", user="test_user", password="test_pass", health_check_interval=1 ) # 执行健康检查 is_healthy = pool.health_check() print(f"✅ 健康检查结果: {is_healthy}") # 获取健康统计 health_stats = pool.get_health_stats() print(f"✅ 健康统计:") print(f" 健康连接: {health_stats['healthy_connections']}") print(f" 不健康连接: {health_stats['unhealthy_connections']}") print(f" 健康检查次数: {health_stats['health_check_count']}") pool.close() def demo_thread_safety(): """演示线程安全""" print("\n" + "="*60) print("演示5: 连接池线程安全") print("="*60) pool = ConnectionPool( min_connections=2, max_connections=10, host="localhost", port=3306, database="test_db", user="test_user", password="test_pass" ) errors = [] connections = [] lock = threading.Lock() def get_connection_task(thread_id: int): try: conn = pool.get_connection(timeout=5) with lock: connections.append(conn) time.sleep(0.1) # 模拟使用 pool.release_connection(conn) except Exception as e: with lock: errors.append(str(e)) # 创建10个线程并发获取连接 threads = [] for i in range(10): t = threading.Thread(target=get_connection_task, args=(i,)) threads.append(t) t.start() for t in threads: t.join() print(f"✅ 10个线程并发获取连接完成") print(f"✅ 错误数: {len(errors)}") print(f"✅ 成功获取连接数: {len(connections)}") pool.close() def demo_pool_manager(): """演示连接池管理器""" print("\n" + "="*60) print("演示6: 连接池管理器") print("="*60) # 创建多个命名连接池 user_pool = pool_manager.create_pool( "user_db", min_connections=2, max_connections=5, host="localhost", port=3306, database="user_db", user="user", password="pass" ) order_pool = pool_manager.create_pool( "order_db", min_connections=2, max_connections=5, host="localhost", port=3306, database="order_db", user="order", password="pass" ) print("✅ 创建2个命名连接池: user_db, order_db") # 获取指定连接池 retrieved_user_pool = pool_manager.get_pool("user_db") retrieved_order_pool = pool_manager.get_pool("order_db") print(f"✅ 获取user_db连接池: {retrieved_user_pool is user_pool}") print(f"✅ 获取order_db连接池: {retrieved_order_pool is order_pool}") # 获取所有统计信息 all_stats = pool_manager.get_all_stats() print(f"✅ 所有连接池统计: {list(all_stats.keys())}") for name, stats in all_stats.items(): print(f" {name}: 总连接数={stats['total_connections']}") pool_manager.close_all() print("✅ 关闭所有连接池") def main(): """主函数""" print("\n" + "="*60) print("数据库连接池管理模块演示") print("="*60) demo_basic_operations() demo_capacity_limit() demo_statistics() demo_health_check() demo_thread_safety() demo_pool_manager() print("\n" + "="*60) print("✅ 所有演示完成!") print("="*60) if __name__ == "__main__": main()