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

利用 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():等待所有线程执行完毕输出结果

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

相关推荐
boy快快长大1 天前
EasyTier初次使用
服务器
2501_915909061 天前
Windows 上用 VS Code 调试 iPhone 真机 App,KXBuild 断点、崩溃定位实操
ide·windows·vscode·ios·iphone·个人开发·敏捷流程
zuiyuewentian1 天前
借助 AI 在 Win11 上搭建 Rocky Linux:用 Visual Studio 直接调试 Linux 服务
linux·运维·visual studio
牢姐与蒯1 天前
WSL2 迁移教程:把Ubuntu+WSL2从C盘挪到别的盘
linux·运维·服务器·网络·ubuntu·1024程序员节
垆边人似月.1 天前
RDMA 文件传输踩坑(二):为什么 `sleep()` 不能保证接收端准备好了?
linux·服务器·网络·rdma
情 九1 天前
MCP 开发环境搭建:Mac 与 Windows 跑通 Python 服务和 stdio 客户端
windows·python·macos·mcp
DYWorker0011 天前
第 1-10 课: 横切设施:锁、RCU、安全与观测怎么选?
linux
臻一1 天前
rk3568---ftp无法连接
linux·ftp·3568
云飞云共享云桌面1 天前
智能装备工厂研发部门多设计师共享一台SolidWorks服务器做设备装配建模
运维·服务器·网络·人工智能·3d·自动化·制造
简简单单就是我_hehe1 天前
一次 ClickHouse 服务器磁盘告警的排查与修复实录
java·服务器·前端