Locust初探
Locust是一款類似於Jmeter開源負載測試工具,所不同的是它是用python實現,並支持python腳本。 locust提供web ui界面,能夠方便用戶實時監控腳本運行狀態。
Locust安裝
這個框架基於python,故而需要先安裝python,這里不再贅述。
pip install -U pyzmq
pip install -U locustio
使用以上命令安裝
實戰
以公司的項目登錄模塊實戰,直接上代碼
from locust import HttpLocust, TaskSet, task import json class UserBehavior(TaskSet): token = '' userId = '' headers = '' def login(self): data = { "email": "xxxxxxx", "passwd": "xxxxxxx", } headers = { 'Content-Type': 'application/json', 'Accept': 'application/json'} response = self.client.post( 'xxxxxx/login', data=json.dumps(data), headers=headers) content = json.loads(response.content) self.token = {"token": content['data']['token']} self.userId = content['data']['userId'] def logout(self): with self.client.get('xxxxxx/logout', params=self.token, catch_response=True) as response: if response.status_code != 200: response.failure() def user_details(self): data = {'userId': self.userId} with self.client.get('xxxxxxxx/view', params=data, headers=self.headers, catch_response=True) as response: if response.status_code != 200: response.failure() @task(10) def login_logout(self): self.login() self.user_details() self.logout() class WebsiteUser(HttpLocust): host = 'http://10.1.51.221:7600/' task_set = UserBehavior min_wait = 5000 max_wait = 9000
執行壓力測試
重新打開cmd窗口進入腳本文件的目錄之中,執行以下命令開啟壓力測試
locust -f locustfile.py
執行完上面命令后用瀏覽打開http://127.0.0.1:8089,出現以下界面:

我這里嘗試模擬100個虛擬用戶,每秒發送30次請求,然后點擊Start swarming開始進行壓力測試
測試結果
在locust的運行界面,可以下載當前的運行結果到本地,但是這兩份csv中的測試結果不夠詳細,不利於分析系統的瓶頸,這也是locust的不足之處。
