Locust压测MySQL时界面RPS持续为0的问题排查求助
问题根源与排查解决思路
核心问题:你使用了HttpUser类但直接执行MySQL数据库查询,Locust的默认统计系统仅追踪HTTP请求,这类直接的数据库操作不会被自动计入RPS(每秒请求数)统计,所以界面显示RPS为0。
具体解决步骤
1. 替换用户类为User而非HttpUser
HttpUser是Locust专门为HTTP请求场景设计的基类,继承它但不发起HTTP请求时,Locust不会将你的数据库任务纳入统计体系。改为继承通用的User类,再手动上报请求统计。
2. 手动上报数据库请求到Locust统计系统
通过Locust的events.request.fire()方法,将MySQL查询的执行时间、结果状态等信息上报给统计系统,这样就能在界面上看到RPS、响应时间等数据。
修改后的代码示例:
from locust import User, task, between, events from mysql.connector import connect, Error import time class MyUser(User): wait_time = between(1, 5) @task(1) def get_price(self): start_time = time.time() try: with connect( host="192.168.0.9", user="root", password="123", database="test1", port=3306 ) as connection: with connection.cursor() as cursor: cursor.execute("SELECT preco FROM estoque WHERE id_codigo_barras = %s", ("3756392598566",)) result = cursor.fetchone() price = result[0] print("Preço do produto: {}".format(price)) # 上报成功的请求统计 events.request.fire( request_type="MySQL", name="SELECT preco FROM estoque", response_time=(time.time() - start_time) * 1000, # 转换为毫秒单位 response_length=0, # 数据库查询可填0或实际返回数据长度 exception=None ) except Error as e: print(e) # 上报失败的请求统计 events.request.fire( request_type="MySQL", name="SELECT preco FROM estoque", response_time=(time.time() - start_time) * 1000, response_length=0, exception=e )
3. 移除无用的--host参数
你没有发起HTTP请求,启动命令中的--host=http://localhost:8080属于无效配置,可直接删除,避免混淆。修改后的启动命令:
locust -f advanced/tools/direct_locust_loadtest.py
额外排查点
- 升级Locust版本:部分旧版本对自定义事件上报的支持存在缺陷,执行
pip install --upgrade locust更新到最新稳定版。 - 验证任务执行频率:若设置的
wait_time为1-5秒,且初始用户数较少,RPS数值会偏低,但只要终端有输出,说明任务在正常执行,上报统计后界面会显示对应数据。
内容的提问来源于stack exchange,提问作者Alyson Jhones
相关产品推荐
相关产品推荐

