尧图建网站 尧图建网站 YAOTU WEB BUILD 免费咨询
ARTICLE DETAIL

资讯详情

深耕网站建设与建站编程的一线实战洞察。

多线程实现网页接口并发压力测试

多线程实现网页接口并发压力测试 利用 Python threading 多线程 requests 实现简易 GET 接口并发压测适合本地自测接口并发能力。使用线程锁解决多线程计数错乱问题。⚠️警告仅允许测试自己本地服务未经许可压测其他服务器属于违法行为。依赖安装bash运行pip install requests源码python运行import threading import requests thread_count 4 req_count 1000 target_url 127.0.0.1 success_count 1000 lock threading.Lock() def task(): global success_count for _ in range(req_count): try: resp requests.get(target_url, timeout10) if resp.status_code 200: with lock: success_count 1 print(f✅成功累计{success_count}) else: print(f❌状态码{resp.status_code}) except Exception as e: print(f请求异常:{e}) if __name__ __main__: thread_list [] for _ in range(thread_count): t threading.Thread(targettask, daemonTrue) t.start() thread_list.append(t) for t in thread_list: t.join() print(f\n压测结束成功总请求{success_count})简单说明thread_count并发线程数req_count每个线程请求次数Lock保证多线程下计数器准确join()等待所有线程执行完毕输出结果本代码仅用于学习禁止用于非法测试。
返回列表