locust 同机多worker 一键启动

locust分布式时,需借助命令locust 一个一个启动worker,在使用中有点繁琐,

下面借助于多进程,按既定worker数量,一键启动;

 

class WebsiteUser(HttpUser):
    tasks = [TaskSet]
    host = "https://www.baidu.com"
    wait_time = between(0, 0)

def processFun(cmd):
    os.system(cmd)


def start_by_process(tst_locust_file, slave_num, master_host='127.0.0.1', locust_web_port=8090, no_web=False,
                     user_num=10, user_rate=1, result_log='result.log', run_log='run.log'):
    p_lst = []
    if no_web:
        slave_cmd = f"locust -f {tst_locust_file}  --worker --master-host={master_host}"
        master_cmd = f"locust -f {tst_locust_file} --headless -u {user_num} -r {user_rate} --master"
    else:
        slave_cmd = f"locust -f {tst_locust_file}  --worker --master-host={master_host}"
        master_cmd = f"locust -f {tst_locust_file} --web-host {master_host} --web-port {locust_web_port} --master"
    master_cmd += f' --logfile {result_log} --loglevel INFO 1>{run_log} 2>&1'
    # 启动master
    process_master = multiprocessing.Process(target=processFun, args=(master_cmd,))
    process_master.start()
    p_lst.append(process_master)
    # 启动 worker
    for index_num in range(slave_num):
        process = multiprocessing.Process(target=processFun, args=(slave_cmd,))
        process.start()
        p_lst.append(process)

    # 阻塞等待
    for process in p_lst:
        process.join()
        
        
if __name__ == "__main__":
    tst_locust_path = 'wms/wms_test'
    slave_num = 3  # 计划所启动worker数量, 不可超过运行机的CPU数量
    master_host = '127.0.0.1'
    master_host = '192.168.1.102'
    locust_web_port = 8099  # locust web页面挂载端口
    no_web = False
    tst_locust_file = os.path.basename(__file__)  # 本脚本名
    os.chdir(os.getcwd().replace(tst_locust_path.replace('/', os.sep), ''))
    tst_locust_file = f'{tst_locust_path}/{tst_locust_file}'
    start_by_process(tst_locust_file, slave_num, master_host, locust_web_port, no_web=no_web)

 

posted on 2022-01-22 15:38  旧楚布衣  阅读(494)  评论(0编辑  收藏  举报