Locust与Jmeter对比:
发压能力:相同并发下,Locust(使用FastHttpLocust)> Jmeter
并发能力:Locust和Jmeter旗鼓相当,都能满足工作需求,Jmeter消耗的内存更高
结果报表:Jmeter好于Locust,但是基本都满足工作需求
学习成果:Jmeter>Locust
易用性:Jmeter > Locust
locust可以实现模拟大批量用户,并且跟踪每个用户的请求数量、失败数、平均响应时间,jmeter就没有这个效果,只是一个汇总的测试结果,并且locust适合mqtt这种千、万级请求,jmeter性能就没有这么强
下面的代码默认已经安装好相关依赖
import paho.mqtt.client as mqtt
import time
import random
from locust import TaskSet, task, User, constant_pacing, between, events
HOST = "127.0.0.1" # 服务器ip
PORT = 15675
COUNTClient = 0
def fire_locust_success(**kwargs):
events.request_success.fire(**kwargs)
def increment():
global COUNTClient
COUNTClient = COUNTClient+1
def time_delta(t1, t2):
return int((t2 - t1)*1000)
def on_message(client, userdata, msg):
print(msg.topic+" "+msg.payload.decode("utf-8"))
# 消息处理
def client_loop():
start_time = time.time()
# client_id = str(int(time.time()) + COUNTClient)
client_id = str(1000 + COUNTClient)
client = mqtt.Client(client_id, transport="websockets") # ClientId不能重复;协议为websockets
client.username_pw_set("username", "password") # 账号密码,一般都需要设置
client.ws_set_options("/ws") # 协议路径
res = client.connect(HOST, PORT, 10) # 建立连接
increment()
name = "device" + str(COUNTClient)
le = len(str(res))
def on_connect(client, userdata, flags, rc):
"""
改写locust中的返回,不然压测界面没有返回数据
"""
end_time = time.time()
if rc == 0:
events.request_success.fire(
request_type='MQTT',
name='name',
response_time=time_delta(start_time, end_time),
response_length=le
)
else:
events.request_failure.fire(
request_type='MQTT',
name=name,
response_time=time_delta(start_time, end_time),
response_length=le,
exception=rc
)
client.on_connect = on_connect
client.on_message = on_message
res2 = client.subscribe("/USER20220815/ADMIN/WEB/MC/NOTICE", qos=0)
print("Response json:", str(client_id)+str(res))
print(str(22222) + str(res2) + str(3333))
client.loop_forever()
class TheTaskSet(TaskSet):
def on_start(self):
print("开始的时候执行")
def on_stop(self):
print("结束的时候执行")
@task
def task_1(self):
client_loop()
class TheUser(User):
tasks = [TheTaskSet]
# wait_time = between(1, 2)
wait_time = constant_pacing(1)