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:每秒钟请求的个数, 在进行性能测试时,要参考设置的并发数进行分析

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

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

查看生成的数据。

相关推荐
带娃的IT创业者1 分钟前
解密OpenClaw系列11-OpenClaw自动更新系统
开发语言·软件工程·自动更新·软件发布·ai智能体·openclaw·桌面智能体
skywalk816311 分钟前
Diffusers 库介绍,它支持LTX-2模型
python
编程小风筝1 小时前
编写java代码如何写文档注释?
java·开发语言
lly2024061 小时前
HTML 媒体(Media)
开发语言
一个处女座的程序猿O(∩_∩)O1 小时前
Python函数参数*args和**kwargs完全指南:从入门到精通
开发语言·python
与衫1 小时前
如何将SQLFlow工具产生的血缘导入到Datahub平台中
java·开发语言·数据库
m0_531237171 小时前
C语言-分支与循环语句练习
c语言·开发语言
Never_Satisfied1 小时前
在JavaScript / HTML中,在html的元素中寻找第X个某元素
开发语言·javascript·html
好家伙VCC1 小时前
**发散创新:编译器优化实战——从LLVM IR到性能飞跃的奇妙旅程**
java·开发语言·python·算法
游乐码1 小时前
c#成员属性
开发语言·c#