Locust 官方文檔 10:將 Locust 作為庫(kù)來使用

It’s possible to use Locust as a library, instead of running Locust using the locust command.

將 Locust 作為 Python 的一個(gè)三方庫(kù),通過 Python 代碼運(yùn)行,代替命令行的方式。

To run Locust as a library you need to create an Environment instance:

通過 Python 代碼來運(yùn)行,你需要?jiǎng)?chuàng)建 Environment 的實(shí)例:

from locust.env import Environment

env = Environment(user_classes=[MyTestUser])

The Environment instance’s create_local_runner, create_master_runner or create_worker_runner can then be used to start a Runner instance, which can be used to start a load test:

Environment 實(shí)例中的 Runner 用來使用不同的方式啟動(dòng)負(fù)載測(cè)試,分別為 create_local_runner, create_master_runnercreate_worker_runner。

env.create_local_runner()
env.runner.start(5000, hatch_rate=20)
env.runner.greenlet.join()

We could also use the Environment instance’s create_web_ui method to start a Web UI that can be used to view the stats, and to control the runner (e.g. start and stop load tests):

也可以使用 Environment 實(shí)例中的 create_web_ui 方法來啟動(dòng) web UI 以便控制運(yùn)行(啟動(dòng)或停止負(fù)載測(cè)試)和查看統(tǒng)計(jì)信息:

env.create_local_runner()
env.create_web_ui()
env.web_ui.greenlet.join()

3# Full example 完整示例

import gevent
from locust import HttpUser, task, between
from locust.env import Environment
from locust.stats import stats_printer
from locust.log import setup_logging

setup_logging("INFO", None)


class User(HttpUser):
    wait_time = between(1, 3)
    host = "https://docs.locust.io"

    @task
    def my_task(self):
        self.client.get("/")

    @task
    def task_404(self):
        self.client.get("/non-existing-path")

# setup Environment and Runner
# 設(shè)置 Environment 和 Runner
env = Environment(user_classes=[User])
env.create_local_runner()

# start a WebUI instance
# 啟動(dòng) WebUI 實(shí)例
env.create_web_ui("127.0.0.1", 8089)

# start a greenlet that periodically outputs the current stats
# 啟動(dòng) greenlet 定期輸出當(dāng)前的統(tǒng)計(jì)信息
gevent.spawn(stats_printer(env.stats))

# start the test
# 啟動(dòng)負(fù)載測(cè)試
env.runner.start(1, hatch_rate=10)

# in 60 seconds stop the runner
# 運(yùn)行 60s 后停止運(yùn)行
gevent.spawn_later(60, lambda: env.runner.quit())

# wait for the greenlets
# 等待 greenlets
env.runner.greenlet.join()

# stop the web server for good measures
# 采取良好的措施停止 web server
env.web_ui.stop()
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容