对于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