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

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

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

相关推荐
AxureMost10 分钟前
Dopamine 3.0.10 音乐播放器
windows
MayZork10 分钟前
Windows 与 Linux 下 vcpkg 的安装部署指南
linux·运维·windows
yyuuuzz13 分钟前
记一次 VPS 性能排查:共享 CPU 突发额度导致的限流
运维·服务器·人工智能
冰雪青松18 分钟前
Ubuntu 运维命令大全:从入门到精通的实战参考手册
运维·服务器·ubuntu
前端 贾公子32 分钟前
第09章:上下文与记忆 (2)
java·服务器·前端
zbyyd40 分钟前
Linux 进程间通信学习笔记
linux·笔记·学习
CDN36042 分钟前
节点智能调度实操:解决出海区域访问快慢不均、节点拥堵、跨洋延迟高,CDN 全网择优落地方案
运维·服务器·网络
Source.Liu1 小时前
【Dioxus】Windows 环境下 Rust + Dioxus 安装配置笔记
windows·rust·dioxus
roman_日积跬步-终至千里1 小时前
【数据治理(6)】DataOps 不是调度工具,而是让数据产品长期可信的运行机制
java·服务器·网络
落魄大学生之流水线上谋生计2 小时前
LangGraph 基本用法指南
java·windows·python·langchain