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

利用 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, timeout=10)
            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(target=task, daemon=True)
        t.start()
        thread_list.append(t)
    for t in thread_list:
        t.join()
    print(f"\n🎉压测结束,成功总请求:{success_count}")

简单说明

  1. thread_count:并发线程数
  2. req_count:每个线程请求次数
  3. Lock:保证多线程下计数器准确
  4. join():等待所有线程执行完毕输出结果

本代码仅用于学习,禁止用于非法测试。

相关推荐
JXJD20042 小时前
AI 推理服务器高速连接器线束自动化设备定制指南 全场景互连非标整线方案参考
服务器·人工智能·自动化
jufeng13072 小时前
【系列:MiniKV 原理剖析 · 第 2 篇】
linux·c++·软件工程
王琦03182 小时前
Linux的管理程序
linux·运维·服务器
%d%d22 小时前
Windows 本地部署小红书 MCP + OpenAI Tunnel + ChatGPT 接入全流程
windows·chatgpt
QWEDDRFTG3 小时前
家用服务器供电
服务器
Crazy________3 小时前
Redis02:库切换、监控与安全配置
linux·redis·云原生·mybatis
Eloudy3 小时前
给 Linux 加新硬盘的挂载命令
linux·运维·服务器
三言老师3 小时前
ss高效查看网络连接端口实操
linux·运维·服务器·网络
三言老师3 小时前
traceroute路由追踪实操
linux·运维·服务器·网络