溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

怎么安裝和使用Python輕量級(jí)性能工具Locust

發(fā)布時(shí)間:2023-05-09 10:58:11 來(lái)源:億速云 閱讀:91 作者:zzz 欄目:編程語(yǔ)言

這篇文章主要介紹“怎么安裝和使用Python輕量級(jí)性能工具Locust”的相關(guān)知識(shí),小編通過(guò)實(shí)際案例向大家展示操作過(guò)程,操作方法簡(jiǎn)單快捷,實(shí)用性強(qiáng),希望這篇“怎么安裝和使用Python輕量級(jí)性能工具Locust”文章能幫助大家解決問(wèn)題。

Locust基于python的協(xié)程機(jī)制,打破了線程進(jìn)程的限制,可以能夠在一臺(tái)測(cè)試機(jī)上跑高并發(fā)

性能測(cè)試基礎(chǔ)

  1.快慢:衡量系統(tǒng)的處理效率:響應(yīng)時(shí)間

  2.多少:衡量系統(tǒng)的處理能力:?jiǎn)挝粫r(shí)間內(nèi)能處理多少個(gè)事務(wù)(tps)

性能測(cè)試根據(jù)測(cè)試需求最常見(jiàn)的分為下面三類

  1 負(fù)載測(cè)試load testing

    不斷向服務(wù)器加壓,值得預(yù)定的指標(biāo)或者部分系統(tǒng)資源達(dá)到瓶頸,目的是找到系統(tǒng)最大負(fù)載的能力

  2 壓力測(cè)試

    通過(guò)高負(fù)載持續(xù)長(zhǎng)時(shí)間,來(lái)驗(yàn)證系統(tǒng)是否穩(wěn)定

  3 并發(fā)測(cè)試:

    同時(shí)像服務(wù)器提交請(qǐng)求,目的發(fā)現(xiàn)系統(tǒng)是否存在事務(wù)沖突或者鎖升級(jí)的現(xiàn)象

性能負(fù)載模型

怎么安裝和使用Python輕量級(jí)性能工具Locust

locust安裝

安裝存在問(wèn)題,可以通過(guò)豆瓣源下載

pip install locust
locust模板

基本上多數(shù)的場(chǎng)景我們都可以基于這個(gè)模板read.py去做修改

from locust import HttpUser, TaskSet, task, tag, events
# 啟動(dòng)locust時(shí)運(yùn)行
@events.test_start.add_listener
def setup(environment, **kwargs):
    # print("task setup")
# 停止locust時(shí)運(yùn)行
@events.test_stop.add_listener
def teardown(environment, **kwargs):
    print("task teardown")
class UserBehavor(TaskSet):
    #虛擬用戶啟用task運(yùn)行
    def on_start(self):
        print("start")
        locusts_spawned.wait()
    #虛擬用戶結(jié)束task運(yùn)行
    def on_stop(self):
        print("stop")
    @tag('test1')
    @task(2)
    def index(self):
        self.client.get('/yetangjian/p/17320268.html')
    @task(1)
    def info(self):
        self.client.get("/yetangjian/p/17253215.html")
class WebsiteUser(HttpUser):
    def setup(self):
        print("locust setup")
    def teardown(self):
        print("locust teardown")
    host = "https://www.cnblogs.com"
    task_set = task(UserBehavor)
    min_wait = 3000
    max_wait = 5000

注:這里我們給了一個(gè)webhost,這樣我們可以直接在瀏覽器中打開(kāi)locust

集合點(diǎn)lr_rendezvous

當(dāng)然我們可以把集合點(diǎn)操作放入上述模板的setup中去運(yùn)行起來(lái)

locusts_spawned = Semaphore()
locusts_spawned.acquire()
def on_hatch_complete(**kwargs):
    """
    select_task類的鉤子函數(shù)
    :param kwargs:
    :return:
    """
    locusts_spawned.release()
events.spawning_complete.add_listener(on_hatch_complete)
n = 0
class UserBehavor(TaskSet):
    def login(self):
        global n
        n += 1
        print(f"第{n}個(gè)用戶登陸")
    def on_start(self):
        self.login()
        locusts_spawned.wait()
    @task
    def test1(self):
        #catch_response獲取返回
        with self.client.get("/yetangjian/p/17253215.html",catch_response=True):
            print("查詢結(jié)束")
class WebsiteUser(HttpUser):
    host = "https://www.cnblogs.com"
    task_set = task(UserBehavor)
    wait_time = between(1,3)
if __name__ == '__main__':
    os.system('locust -f read.py --web-host="127.0.0.1"')
比較常見(jiàn)的用法

在上面兩個(gè)例子中我們已經(jīng)看到了一些,例如裝飾器events.test_start.add_listener;events.test_stop.add_listener用來(lái)在負(fù)載測(cè)試前后進(jìn)行一些操作,又例如on_start、on_stop,在task執(zhí)行前后運(yùn)行,又例如task,可以用來(lái)分配任務(wù)的權(quán)重

等待時(shí)間

# wait between 3.0 and 10.5 seconds after each task
#wait_time = between(3.0, 10.5)
#固定時(shí)間等待
# wait_time = constant(3)
#確保每秒運(yùn)行多少次
constant_throughput(task_runs_per_second)
#確保每多少秒運(yùn)行一次
constant_pacing(wait_time)

同樣也可以在User類下發(fā)重寫wait_time來(lái)達(dá)到自定義

tag標(biāo)記

@tag('test1')
@task(2)
def index(self):
    self.client.get('/yetangjian/p/17320268.html')

通過(guò)對(duì)任務(wù)打標(biāo)記,就可以在運(yùn)行時(shí)候執(zhí)行運(yùn)行某一些任務(wù):

#只執(zhí)行標(biāo)記test1
os.system('locust -f read.py --tags test1 --web-host="127.0.0.1"')
#不執(zhí)行標(biāo)記過(guò)的
os.system('locust -f read.py --exclude-tags --web-host="127.0.0.1"')
#除去test1執(zhí)行所有
os.system('locust -f read.py --exclude-tags test1 --web-host="127.0.0.1"')

自定義失敗

#定義響應(yīng)時(shí)間超過(guò)0.1就為失敗
with self.client.get("/yetangjian/p/17253215.html", catch_response=True) as response:
    if response.elapsed.total_seconds() > 0.1:
        response.failure("Request took too long")
#定義響應(yīng)碼是200就為失敗
with self.client.get("/yetangjian/p/17320268.html", catch_response=True) as response:
    if response.status_code == 200:
        response.failure("響應(yīng)碼200,但我定義為失敗")

怎么安裝和使用Python輕量級(jí)性能工具Locust

自定義負(fù)載形狀

自定義一個(gè)shape.py通過(guò)繼承LoadTestShape并重寫tick

這個(gè)形狀類將以100塊為單位,20速率的增加用戶數(shù),然后在10分鐘后停止負(fù)載測(cè)試(從運(yùn)行開(kāi)始的第51秒開(kāi)始user_count會(huì)round到100)

from locust import LoadTestShape
class MyCustomShape(LoadTestShape):
    time_limit = 600
    spawn_rate = 20
    def tick(self):
        run_time = self.get_run_time()
        if run_time < self.time_limit:
            # User count rounded to nearest hundred.
            user_count = round(run_time, -2)
            return (user_count, self.spawn_rate)
        return None

運(yùn)行圖如下所示

怎么安裝和使用Python輕量級(jí)性能工具Locust

通過(guò)命令行去觸發(fā)

os.system('locust -f read.py,shape.py --web-host="127.0.0.1"')

不同時(shí)間階段的例子

from locust import LoadTestShape
class StagesShapeWithCustomUsers(LoadTestShape):
    stages = [
        {"duration": 10, "users": 10, "spawn_rate": 10},
        {"duration": 30, "users": 50, "spawn_rate": 10},
        {"duration": 60, "users": 100, "spawn_rate": 10},
        {"duration": 120, "users": 100, "spawn_rate": 10}]
    def tick(self):
        run_time = self.get_run_time()
        for stage in self.stages:
            if run_time < stage["duration"]:
                tick_data = (stage["users"], stage["spawn_rate"])
                return tick_data
        return None

關(guān)于“怎么安裝和使用Python輕量級(jí)性能工具Locust”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識(shí),可以關(guān)注億速云行業(yè)資訊頻道,小編每天都會(huì)為大家更新不同的知識(shí)點(diǎn)。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI