利用 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}")
简单说明
thread_count:并发线程数req_count:每个线程请求次数Lock:保证多线程下计数器准确join():等待所有线程执行完毕输出结果
本代码仅用于学习,禁止用于非法测试。