以下是针对mysql 数据库的测试,全部是查询测试部分,实际情况模拟会非常复杂。见以下代码。
import threading import pymysql import random # 单库多线程访问,select,正常情况一台机器一个库,因表数量,大小,分布有所不同,还要看模拟 实际业务统计情况 # 包括单表访问,相同select, # 多表访问, # 模拟现实场景:多表select, 多表update, select:update = 2:1 # city,country ,countrylanguage,slb_access_log,slb_stat_data # 连接到MySQL数据库的配置 config = { 'host': 'localhost', 'user': 'root', 'password': 'liuyunqiu', 'database': 'world' } # 模拟高负载的函数 def high_load_function(thread_id): try: connection = pymysql.connect(**config) if connection.open: cursor = connection.cursor() table_list =['city','country','countrylanguage','slb_access_log','slb_stat_data'] table = random.choice(table_list) cursor.execute(f"SELECT * FROM {table}") # 替换为您的表名和查询 print(f"Thread {thread_id} - Database version : {cursor.fetchone()}") cursor.close() connection.close() except pymysql.Error as e: print(f"Error {e} in Thread {thread_id}") # 创建并启动多线程 def start_threads(number_of_threads): threads = [] for i in range(number_of_threads): thread = threading.Thread(target=high_load_function, args=(i,)) threads.append(thread) thread.start() for t in threads: t.join() # 设置并发线程数和启动测试 number_of_threads = 500 # 根据需要调整并发线程数 start_threads(number_of_threads)
##测试结果,共500个连接,其中400个正常返回了,有100个报错,显示:too many connections, 此处也可查看数据库连接数设置,显示151,估计是数据库查询比较简单,表也比较小,占用资源比较快,在同时到达 151时,部分连接报错说是超出连接数被打回。但是可见大部分连接400个还是正常地完成了。
出问题的基本是后100个,