locust 压测 websocket

* 安装 python 3.8

https://www.python.org/

py --version

* 安装 locust

pip install locust==2.5.1 -i http://pypi.douban.com/simple/

pip install locust==2.5.1 -i https://pypi.mirrors.ustc.edu.cn/simple/

locust -V

备注:-i 是切换下载源

* 安装依赖

pip install websockets

pip install websocket

pip install websocket_client

* 新建文件 main.py

python 复制代码
import time
import websocket
from locust import User, task, between, events

class WebSocketUser(User):
    wait_time = between(1, 2)

    def on_start(self):
        self.connection_status = False
        try:
            self.client = websocket.create_connection("ws://127.0.0.1:7777")
            self.connection_status = True
            events.request_success.fire(request_type="ws connect", name="connect Success",  response_time=0, response_length=0)
        except Exception as e:
            print(e)
            events.request_failure.fire(request_type="ws connect", name="connect Fail", exception=e, response_time=0, response_length=0)
        

    def on_stop(self):
        if self.connection_status:
            self.client.close()

    @task
    def ws_task(self):
        if self.connection_status:
            try:
                request = '{"cmd":"2","subcmd":"1","data":{"account":"daming","password":"daming"}}'
                start_time = time.time()
                self.client.send(request)
                response = self.client.recv()
                # print("response=", response)
                total_time = int((time.time() - start_time) * 1000)
                events.request_success.fire(request_type="ws send", name="Send Success", response_time=total_time, response_length=0)
            except Exception as e:
                total_time = int((time.time() - start_time) * 1000)
                events.request_failure.fire(request_type="ws send", name="Send Fail", exception=e, response_time=total_time, response_length=0)

* 进入到路径下

locust -f main.py

* 网页查看

http://localhost:8089/

搞1000个号去连接 每秒连接数为10个号

查看:RPS:每秒钟请求的个数, 在进行性能测试时,要参考设置的并发数进行分析

没有点击 停止的话会一直执行下去。

把服务器关闭试试 会有发送失败的出现

查看生成的数据。

相关推荐
开心香辣派小星10 小时前
23种设计模式-18观察者(Observer)模式
java·开发语言·设计模式
San30.10 小时前
从 Mobile First 到 AI First:用 Python 和大模型让数据库“开口说话”
数据库·人工智能·python
Slow菜鸟10 小时前
Java项目基础架构(一)| 工程架构选型指南
java·开发语言·架构
计算机学姐10 小时前
基于Python的旅游数据分析及可视化系统【2026最新】
vue.js·python·数据挖掘·数据分析·django·旅游·推荐算法
CoderYanger10 小时前
动态规划算法-斐波那契数列模型:1.第N个泰波那契数
开发语言·算法·leetcode·动态规划·1024程序员节
红队it10 小时前
【机器学习】python旅游数据分析可视化协同过滤算法推荐系统(完整系统源码+数据库+开发笔记+详细部署教程)✅
python·mysql·算法·机器学习·数据分析·旅游
曲幽10 小时前
Flask项目结构详解:用蓝图实现优雅的模块化开发
python·web·route·blueprint·register
zore_c10 小时前
【C语言】文件操作详解2(文件的顺序读写操作)
android·c语言·开发语言·数据结构·笔记·算法·缓存
weixin_4211334110 小时前
PyInstaller& Nuitka & 项目 (如 django)
后端·python·django
weixin_4624462310 小时前
使用 Python + Tkinter + openpyxl 实现 Excel 文本化转换
开发语言·python·excel