Locust-当多个虚拟用户执行相同的 post 或 put 时如何避免冲突

问题描述 投票:0回答:0

对于POST、PUT等写操作,有没有办法避免多个虚拟用户执行同一任务时发生冲突?有更好的实现吗?

from locust import HttpUser, task, between
import threading

class MyUser(HttpUser):
    wait_time = between(1, 5)
    write_lock = threading.Lock()  # Threading lock for synchronization

    @task
    def perform_post(self):
        headers = {"Content-Type": "application/json"}
        payload = {"key": "value"}  # Your JSON payload here
        
        with self.write_lock:
            response = self.client.post("/items", json=payload, headers=headers)
    
    @task
    def perform_put(self):
        headers = {"Content-Type": "application/json"}
        payload = {"key": "updated_value"}  # Your JSON payload here
        item_id = 123  # Replace with the actual item ID
        
        with self.write_lock:
            response = self.client.put(f"/items/{item_id}", json=payload, headers=headers)
        
        # Process the response or log as needed
post put locust
© www.soinside.com 2019 - 2024. All rights reserved.