我正在尝试在我的运行中生成的所有
Users
中分发预定义请求有效负载的列表。从概念上讲,我想将 N 个请求列表拆分为 U 个用户,这样每个请求仅向服务器发出一次。
对于单个进程,我可以通过简单地在
__init__
方法中为每个用户分配一个唯一的 id 来实现这一点 - 例如:
class MyUser():
count = 0
def __init__(self, env):
super().__init__(environment)
self.user_id = MyUser.count
MyUser.count += 1
但是,当使用多个进程(通过
--processes=P
)时,显然有多个 MyUser.count
实例,因此 user_ids 不是唯一的。
我可以使用某种集中机制来分配 ID(或某些现有的唯一 ID)吗?
是的!有多种方法,您可以使用工人索引:
self.environment.runner.worker_index
(它从零开始并且是连续的,除非您在运行期间让工人断开连接)
或者您可以在测试期间使用消息传递将数据从 master 提供给worker。通过编写自己的通信:https://docs.locust.io/en/stable/running-distributed.html#communicating-across-nodes,或者您可以使用 locust-plugins Distributor,它提供了迭代器的包装器:https://github.com/SvenskaSpel/locust-plugins?tab=readme-ov-file#distributing-test-data
我还没有测试过这个,但它应该非常接近你想要的:
from locust_plugins.distributor import Distributor
from locust import HttpUser, events
from locust.runners import WorkerRunner
distributors = {}
@events.init.add_listener
def on_locust_init(environment, **_kwargs):
product_iterator = None
if not isinstance(environment.runner, WorkerRunner):
product_iterator = csv.reader("products.csv")
distributors["products"] = Distributor(environment, product_iterator, "products")
class MyUser(HttpUser):
@task
def my_task(self) -> None:
product = next(distributors["products"])
self.client.get(f"/?product={product[0]})