老样子,注释都有
from locust import HttpUser, TaskSet, task
from websocket import create_connection
import json, time, queue
# 建立一个websocket连接
ws = create_connection("wss://XXX.com/websocket?platform=1&token=74348d&bizType=1")
print(f'websocket连接状态:{ws.connected}')
top_num = int(time.time())
class Demo(TaskSet):
@task(66)
def im_socket(self):
if ws.connected == True:
user_num = self.parent.queueData.get_nowait() # 从queueData中取值(该队列循环-先进先出)
self.parent.queueData.put_nowait(user_num) # 将取到的数再丢回队列(后进后出),即可循环使用
message = '{"event":1,"data":{"msgType":1,"sessionId":"1684491776793976832","msgContent":"单个用户单个连接%s消息序号%s"}}'%(top_num,user_num)
print(message)
ws.send(message)
# print(f'接收返回结果:{ws.recv()}')
else:
print(f'websocket连接失败!!!!!!!!!!!!!!!')
class websitUser(HttpUser):
tasks = [Demo] # 指向定义了用户行为的类Demo
queueData = queue.Queue() # 初始化queue队列, 先进先出
for user_num in range(1, 101):
queueData.put_nowait(user_num) # 将测试数据添加至队列
min_wait = 1000 #模拟负载的任务之间执行时的最小等待时间,单位为毫秒
max_wait = 5000
if __name__=="__main__":
import os
os.system("locust -f Locust.py --host=https://xxx.com --headless -u 5 -r 2 -t 30s --html HTML_FILE") #访问地址http://localhost:8089
print('==================关闭连接,任务结束==================')
ws.close()