性能工具之locust簡單上手

前言

最近學習python也想通過python中的locust模塊做性能測試,簡單介紹下。官方網站【https://www.locust.io/

Locust is an easy-to-use, distributed, user load testing tool. It is intended for load-testing web sites (or other systems) and figuring out how many concurrent users a system can handle.

[Locust是一個易於使用,分佈式,用戶負載測試工具。它用於負載測試web站點(或其他系統)並計算一個系統可以處理多少並發用戶。]

The idea is that during a test, a swarm of locusts will attack your website. The behavior of each locust (or test user if you will) is defined by you and the swarming process is monitored from a web UI in real-time. This will help you battle test and identify bottlenecks in your code before letting real users in.

[在測試中,一群蝗蟲會攻擊你的網站。每個蝗蟲(或者測試用戶)的行為由您定義,集群過程由web UI實時監控。這將幫助您在讓真正的用戶進入之前進行測試並識別代碼中的瓶頸。]

Locust is completely event-based, and therefore it』s possible to support thousands of concurrent users on a single machine. In contrast to many other event-based apps it doesn』t use callbacks. Instead it uses light-weight processes, through gevent. Each locust swarming your site is actually running inside its own process (or greenlet, to be correct). This allows you to write very expressive scenarios in Python without complicating your code with callbacks.

[Locust完全是基於事件的,因此在一台機器上支持數千個並發用戶是可能的。與許多其他基於事件的應用程序不同,它不使用回調。相反,它通過gevent使用輕量級進程。每個聚集在你的站點上的蝗蟲實際上是在它自己的進程中運行的(或者說是greenlet)。這允許您用Python編寫非常有表現力的場景,而不用回調使代碼複雜化。]

幫助文檔【https://docs.locust.io/en/stable/what-is-locust.html

安裝

前置條件本機安裝了python環境

pip install locustio

locust –help

Usage: locust [options] [LocustClass [LocustClass2 ... ]]  Options:  -h, --help            show this help message and exit  -H HOST, --host=HOST  Host to load test in the following format:                        http://10.21.32.33  --web-host=WEB_HOST   Host to bind the web interface to. Defaults to '' (all                        interfaces)  -P PORT, --port=PORT, --web-port=PORT                        Port on which to run web host  -f LOCUSTFILE, --locustfile=LOCUSTFILE                        Python module file to import, e.g. '../other.py'.                        Default: locustfile  --csv=CSVFILEBASE, --csv-base-name=CSVFILEBASE                        Store current request stats to files in CSV format.  --master              Set locust to run in distributed mode with this                        process as master  --slave               Set locust to run in distributed mode with this                        process as slave  --master-host=MASTER_HOST                        Host or IP address of locust master for distributed                        load testing. Only used when running with --slave.                        Defaults to 127.0.0.1.  --master-port=MASTER_PORT                        The port to connect to that is used by the locust                        master for distributed load testing. Only used when                        running with --slave. Defaults to 5557. Note that                        slaves will also connect to the master node on this                        port + 1.  --master-bind-host=MASTER_BIND_HOST                        Interfaces (hostname, ip) that locust master should                        bind to. Only used when running with --master.                        Defaults to * (all available interfaces).  --master-bind-port=MASTER_BIND_PORT                        Port that locust master should bind to. Only used when                        running with --master. Defaults to 5557. Note that                        Locust will also use this port + 1, so by default the                        master node will bind to 5557 and 5558.  --expect-slaves=EXPECT_SLAVES                        How many slaves master should expect to connect before                        starting the test (only when --no-web used).  --no-web              Disable the web interface, and instead start running                        the test immediately. Requires -c and -r to be                        specified.  -c NUM_CLIENTS, --clients=NUM_CLIENTS                        Number of concurrent Locust users. Only used together                        with --no-web  -r HATCH_RATE, --hatch-rate=HATCH_RATE                        The rate per second in which clients are spawned. Only                        used together with --no-web  -t RUN_TIME, --run-time=RUN_TIME                        Stop after the specified amount of time, e.g. (300s,                        20m, 3h, 1h30m, etc.). Only used together with --no-                        web  -L LOGLEVEL, --loglevel=LOGLEVEL                        Choose between DEBUG/INFO/WARNING/ERROR/CRITICAL.                        Default is INFO.  --logfile=LOGFILE     Path to log file. If not set, log will go to                        stdout/stderr  --print-stats         Print stats in the console  --only-summary        Only print the summary stats  --no-reset-stats      [DEPRECATED] Do not reset statistics once hatching has                        been completed. This is now the default behavior. See                        --reset-stats to disable  --reset-stats         Reset statistics once hatching has been completed.                        Should be set on both master and slaves when running                        in distributed mode  -l, --list            Show list of possible locust classes and exit  --show-task-ratio     print table of the locust classes' task execution                        ratio  --show-task-ratio-json                        print json data of the locust classes' task execution                        ratio  -V, --version         show program's version number and exit

前言快速上手demo

# -*- coding: utf-8 -*-# @Time    : 2019/12/31 20:24# @Author  : liwen# @Email   : www.7dtest.com# @File    : SevenLoust.py# coding:utf-8from locust import HttpLocust, TaskSet, task    # HttpLocust 這個類的作用是用來發送http請求的# TaskSet   這個類是定義用戶行為的,相當於loadrunnerhttp協議的腳本,jmeter裏面的http請求一樣,要去幹嘛的# task   這個task是一個裝飾器,它用來把一個函數,裝飾成一個任務,也可以指定他們的先後執行順序  class SevenLoust(TaskSet):    # 自己定義的類,繼承TaskSet,也就是這個類是實現咱們要去請求什麼的    '''打開7DGroup'''      @task(1)  # @task#用task裝飾器把這個函數裝飾成一個咱們要執行的性能任務    def open_7dtest(self):  # 這個函數裏面定義的是咱們要具體做的操作        # 定義requests的請求頭        header = {            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36"}          r = self.client.get("/", headers=header, verify=False)  # 請求這個url裏面的哪個路徑,        print(r.status_code)        assert r.status_code == 200    class websitUser(HttpLocust):    # 這個類繼承了HttpLocust,代表每個並發裏面的每個用戶    task_set = SevenLoust  # 這個是每個用戶都去幹什麼,指定了 SevenLoust 這個類,    min_wait = 3000  # 單位毫秒    max_wait = 6000  # 單位毫秒    if __name__ == "__main__":    import os      # -f是指定一個python文件 後面跟上咱們剛才寫的python文件    # --host是你要訪問哪個網站,後面跟網站的url    os.system("locust -f sevenLoust.py --host=http://www.7dtest.com/7DGroup/")

點擊啟動

提示:

打開瀏覽器顯示:

  • Number of users to simulate 設置虛擬用戶總數
  • Hatch rate (users spawned/second) 每秒啟動虛擬用戶數
  • 點擊Start swarming 開始運行性能測試
  • Type:請求類型;
  • Name:請求路徑;
  • requests:當前請求的數量;
  • fails:當前請求失敗的數量;
  • Median:中間值,單位毫秒,一般服務器響應時間低於該值,而另一半高於該值;
  • Average:所有請求的平均響應時間,毫秒;
  • Min:請求的最小的服務器響應時間,毫秒;
  • Max:請求的最大服務器響應時間,毫秒;
  • Content Size:單個請求的大小,單位位元組;
  • reqs/sec:每秒鐘請求的個數。

Charts圖形顯示

吞吐量/每秒響應事務數(rps)實時統計

平均響應時間/平均事務數實時統計

虛擬用戶數運行

如果停止點擊

總結:

以上是簡單上手demo,只要會python基礎,一看就知道。