簡(jiǎn)介
Locust是一款易于使用的分布式用戶負(fù)載測(cè)試工具。它用于對(duì)網(wǎng)站(或其他系統(tǒng))進(jìn)行負(fù)載測(cè)試,并確定系統(tǒng)可以處理多少并發(fā)用戶。
這個(gè)想法是,在測(cè)試期間,一群蝗蟲(Locust)會(huì)攻擊你的網(wǎng)站。您定義了每個(gè)蝗蟲Locust(或測(cè)試用戶)的行為,并且實(shí)時(shí)地從Web UI監(jiān)視群集過程。這將有助于您在讓真正的用戶進(jìn)入之前進(jìn)行測(cè)試并識(shí)別代碼中的瓶頸。
Locust完全基于事件,因此可以在一臺(tái)計(jì)算機(jī)上支持?jǐn)?shù)千個(gè)并發(fā)用戶。與許多其他基于事件的應(yīng)用程序相比,它不使用回調(diào)。相反,它通過協(xié)程(gevent)機(jī)制使用輕量級(jí)過程。每個(gè)蝗蟲蜂擁到你的網(wǎng)站實(shí)際上是在自己的進(jìn)程內(nèi)運(yùn)行(或者是greenlet,這是正確的)。這允許您在Py??thon中編寫非常富有表現(xiàn)力的場(chǎng)景,而不會(huì)使代碼復(fù)雜化。
locust和jemter差不多,單機(jī)承受并發(fā)量比jmeter大,但是不能設(shè)置起始時(shí)間。
如何使用
#! /usr/bin/env python
# -*- coding: utf-8 -*-
from locust import HttpLocust,TaskSet,task
import os
class GetResume(TaskSet):
@task(1) #設(shè)置權(quán)重值,默認(rèn)為1,值越大,優(yōu)先執(zhí)行
def get_resume(self):
#如果后臺(tái)需要的是json格式,需要加header,否則報(bào)415
header = {"Content-Type": "application/json"}
self.client.headers.update(header)
url1 = "/api/resume/getAllResume"
json = {'currPage': '1', 'pageSize': '10', 'mark':'0'}
# 網(wǎng)上是直接把Json的格式填進(jìn)去,但是在本項(xiàng)目中報(bào)400,無法識(shí)別數(shù)據(jù)格式,查看系統(tǒng)報(bào)錯(cuò)才明白需要轉(zhuǎn)成json對(duì)象
req = self.client.post(url1,json = json)
if req.status_code == 200:
print("success")
else:
print("fail")
@task(1)
def get_schedule(self):
header = {"Content-Type": "application/json"}
url2 = "/api/resume/getAllJobSchedule"
json = {"currPage": "1", "pageSize": "10"}
self.client.headers.update(header)
req = self.client.post(url2,json = json)
print("Response status code:", req.status_code)
assert req.status_code == 200
class websitUser(HttpLocust):
task_set = GetResume
min_wait = 3000 # 單位為毫秒
max_wait = 6000 # 單位為毫秒
if __name__ == "__main__":
os.system("locust -f locustfile.py --host=http://xx.4.xx.22:8080")
執(zhí)行上面編寫的腳本后,本地打開localhost:8089或127.0.0.1:8089即能正常訪問locust的web UI界面,設(shè)置并發(fā)用戶數(shù),執(zhí)行壓測(cè)。

無web-UI模式
在沒有Web UI的情況下運(yùn)行l(wèi)ocust - 可以打開cmd 通過使用--no-web參數(shù),
- -c指定要生成的Locust用戶數(shù)
- -r每秒啟動(dòng)虛擬用戶數(shù)
先cd到腳本當(dāng)前目錄,然后執(zhí)行指令
> locust -f locustfile.py --host=[http://192.168.x.xx:80](http://192.168.x.xx/) --no-web -c 1 -r 1
設(shè)置運(yùn)行時(shí)間
如果要指定測(cè)試的運(yùn)行時(shí)間,可以使用--run-time
> locust -f locustfile.py --host=[http://192.168.x.xx:80](http://192.168.x.xx/) --no-web -c 1 -r 1 --run-time 10
或使用-t參數(shù)
> locust -f locustfile.py --host=[http://192.168.x.xx:80](http://192.168.x.xx/) --no-web -c 1 -r 1 -t 10
運(yùn)行時(shí)間單位,如果不寫單位默認(rèn)是s,也可以指定小時(shí)h,分鐘m,可以參考以下時(shí)間格式
* 10s 10秒(不寫單位默認(rèn)s)
* 5m 表示5分鐘
* 1h 1小時(shí)
* 1m30s 1分30秒
--csv=example參數(shù)保存CSV文件到當(dāng)前腳本目錄example_distribution.csv、example_requests.csv
> locust -f locustfile.py --host=[http://192.168.x.xx:80](http://192.168.x.xx/) --no-web --csv=example -c 1 -r 1 -t 10s
