locust压测mqtt

本文介绍如何使用 Locust 模拟大量用户并发连接 MQTT 服务器,对比 JMeter 的测试效果。Locust 能够跟踪每个用户的详细请求信息,而 JMeter 只提供汇总数据。通过示例代码展示了 Locust 如何设置 MQTT 客户端,连接服务器,并订阅主题。同时,代码中包含了 MQTT 连接、消息处理及性能统计的方法。
摘要由CSDN通过智能技术生成

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)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值