You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

以库模式使用Locust时TimeScale插件初始化事件未触发的解决咨询

库模式下Locust统计数据输出到TimeScaleDB的解决方案

问题背景

在Locust库模式运行时,events.init监听器不会自动触发,导致locust-plugins的TimeScaleDB集成无法通过命令行参数自动初始化,手动传递Namespace参数也无法触发对应的初始化逻辑。

可行解决方案

方案1:手动初始化TimeScale实例

绕过events.init监听器,直接创建TimeScale实例并传入所需配置:

修改后的代码示例:

# Built-in/Generic Imports
import json
import random
import time
import redis
import gevent
import os
import locust_plugins
from locust import User, task, tag
from locust import events
from locust.env import Environment
from locust.log import setup_logging
from locust.stats import stats_printer, stats_history
from argparse import Namespace
# 手动导入Timescale类
from locust_plugins.listeners.timescale import Timescale


# 假设这些环境变量已提前设置
pg_host_env = os.getenv("PG_HOST")
pg_user_env = os.getenv("PG_USER")
pg_password_env = os.getenv("PG_PASSWORD")
pg_port_env = os.getenv("PG_PORT")

test_dict_cmd_args = Namespace()
test_dict_cmd_args.pghost = pg_host_env
test_dict_cmd_args.pguser = pg_user_env
test_dict_cmd_args.pgpassword = pg_password_env
test_dict_cmd_args.pgport = pg_port_env
test_dict_cmd_args.stop_timeout = 0
test_dict_cmd_args.timescale = 1


env = Environment(user_classes=[RedisLocust], events=events)
# 手动初始化Timescale,传入环境和参数
Timescale(
    env=env,
    host=pg_host_env,
    user=pg_user_env,
    password=pg_password_env,
    port=pg_port_env,
)

env.create_local_runner()
gevent.spawn(stats_printer(env.stats))

# 启动保存统计历史的greenlet
gevent.spawn(stats_history, env.runner)

# 开始测试
env.runner.start(user_count=1, spawn_rate=5)

# 10秒后停止测试
gevent.spawn_later(10, lambda: env.runner.quit())

# 等待greenlet完成
env.runner.greenlet.join()

方案2:手动触发init事件

如果想保留locust-plugins原有的初始化逻辑,可以手动触发events.init事件,传入环境和参数:

在创建env对象后添加以下代码:

# 手动触发init事件,传入环境和解析后的参数
events.init.fire(environment=env, parsed_options=test_dict_cmd_args)

修改后的完整代码片段:

env = Environment(user_classes=[RedisLocust], events=events)
# 手动触发init事件
events.init.fire(environment=env, parsed_options=test_dict_cmd_args)

env.create_local_runner()
gevent.spawn(stats_printer(env.stats))
# ... 后续代码不变

原理说明

Locust在命令行模式下会自动解析参数并触发events.init事件,但库模式下不会执行这些流程,因此需要手动完成初始化逻辑——要么直接实例化TimeScale类,要么手动触发init事件来激活locust-plugins的内置逻辑。

内容的提问来源于stack exchange,提问作者aemreg

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 20:15:40