【locust实践】性能测试demo举例

一、Http协议之GET请求demo(无参数化-无缓存):/contact/v3/xxxx接口为例

1、在mac本地安装locust—详细可以百度
本人安装的方法,仅供参考:(直接pip install locustio也可以安装但是 我的mac本这么操作后有问题,环境变量混乱导致无法使用locust)

# github下载locust然后安装之
xxxxxxx@localhost  /yyyyyy/work/locust  git clone https://github.com/locustio/locust/
...(下载完成)... 
xxxxxxx@localhost  /yyyyyy/work/locust  ll
drwxr-xr-x 26 xxxxxxx staff 832B 4 10 11:37 locust
# 然后进入locust目录
xxxxxxx@localhost  /yyyyyy/work/locust  python setup.py install
# 最后check一下locust是否安装成功
xxxxxxx@localhost  /yyyyyy/work/locust  locust -h
...(能正常输出说明没问题)...

2、之后编写自己的locust测试脚本

# 编写locustfile.py文件(文件名需要是locustfile.py这个,因为locust本地运行默认找这个文件,否则会报错没有locustfile.py文件)
 xxxxxxx@localhost  /yyyyyy/work/locust  locust -f locustfile.py --host=http://xx.x.xx.xxx:8380
[2019-04-10 16:07:36,916] localhost/ERROR/locust.main: Could not find any locustfile! Ensure file ends in '.py' and see --help for available options.
xxxxxxx@localhost  /yyyyyy/work/locust  vim locustfile.py    ---demo如下:
from locust import HttpLocust, TaskSet, task

class UserBehavior(TaskSet):
    @task(4)
    def testTask(self):
        r = self.client.get("/contact/v3/xxxx?uid=123123123")
#        print(r.status_code)
#        assert r.status_code == 200

class WebsiteUser(HttpLocust):
    task_set = UserBehavior
    min_wait = 1000
    max_wait = 2000
xxxxxxx@localhost  /yyyyyy/work/locust  ll
total 40
drwxr-xr-x 26 xxxxxxx staff 832B 4 10 11:37 locust
-rwxr-xr-x 1 xxxxxxx staff 453B 4 10 11:57 locustfile.py

3、本地调试自己的压测脚本是否ok

xxxxxxx@localhost  /yyyyyy/work/locust  locust -f locustfile.py --host=http://xx.x.xx.xxx:8380
[2019-04-10 15:29:09,940] localhost/INFO/locust.main: Starting web monitor at *:8089
[2019-04-10 15:29:09,940] localhost/INFO/locust.main: Starting Locust 0.11.1

说明locust已经起来了。可以看到web monitor地址和locust的版本信息。

4、本地浏览器访问:http://127.0.0.1:8089 应该可以看到如下界面
在这里插入图片描述

输入对应的并发用户数和hatch rate,然后start即可开始测试了,然后看看本地的日志,如下显示:

xxxxxxx@localhost  /yyyyyy/work/locust  locust -f locustfile.py --host=http://xx.x.xx.xxx:8380
[2019-04-10 15:29:09,940] localhost/INFO/locust.main: Starting web monitor at *:8089
[2019-04-10 15:29:09,940] localhost/INFO/locust.main: Starting Locust 0.11.1
[2019-04-10 15:29:17,667] localhost/INFO/locust.runners: Hatching and swarming 5 clients at the rate 2 clients/s...
[2019-04-10 15:29:20,181] localhost/INFO/locust.runners: All locusts hatched: WebsiteUser: 5

5、当然locust也支持命令行运行即no-web运行,类似Apache ab 性能测试。

xxxxxxx@localhost  /yyyyyy/work/locust  locust -f locustfile.py --host=http://xx.x.xx.xxx:8380
[2019-04-10 15:29:09,940] localhost/INFO/locust.main: Starting Locust 0.11.1
[2019-04-10 15:29:17,667] localhost/INFO/locust.runners: Hatching and swarming 5 clients at the rate 2 clients/s...
[2019-04-10 15:29:20,181] localhost/INFO/locust.runners: All locusts hatched: WebsiteUser: 5
 Name                                                          # reqs      # fails     Avg     Min     Max  |  Median   req/s
--------------------------------------------------------------------------------------------------------------------------------------------
 GET /contact/v3/feed?uid=138262082                               936    21(2.19%)    1903       9   60085  |     490    0.60
--------------------------------------------------------------------------------------------------------------------------------------------
 Total                                                            936    21(2.24%)                                       0.60

Percentage of the requests completed within given times
 Name                                                           # reqs    50%    66%    75%    80%    90%    95%    98%    99%   100%
--------------------------------------------------------------------------------------------------------------------------------------------
 GET /contact/v3/feed?uid=138262082                                936    490   1000   2500   4500   5300   6100   7200  10000  60000
--------------------------------------------------------------------------------------------------------------------------------------------
 Total                                                             936    490   1000   2500   4500   5300   6100   7200  10000  60000
......
......
......
##### 说明 #####
启动参数:
--no-web 表示不使用Web界面运行测试。
-c 设置虚拟用户数。
-r 设置每秒启动虚拟用户数。
-t 设置设置运行时间。

6、然后强制生成requirements.txt文件,如下操作即可

# 如果提示找不到pipreqs command,pip安装即可
XXXXXXXX@localhost  /yyyyyy/work/locust  pipreqs . --force   
zsh: command not found: pipreqs
XXXXXXXX@localhost  /yyyyyy/work/locust  sudo pip install pipreqs
# 安装完成再次执行即可成功生成requirements.txt文件
XXXXXXXX@localhost  /yyyyyy/work/locust  pipreqs . --force
INFO: Successfully saved requirements file in ./requirements.txt
XXXXXXXX@localhost  /yyyyyy/work/locust  ll
total 40
drwxr-xr-x 26 xxxxxxx staff 832B 4 10 11:37 locust
-rwxr-xr-x 1 xxxxxxx staff 453B 4 10 11:57 locustfile.py
-rw-r--r-- 1 xxxxxxx staff 1.1K 4 10 11:50 locustfile.pyc
-rw-r--r-- 1 xxxxxxx staff 160B 4 10 11:57 requirements.txt

二、Http协议之GET请求demo(参数化):/XXX/v3/xxxx接口为例

暂略—待补充

三、Http协议之POST请求demo(参数化):/XXX/v3/xxxx接口为例

暂略—待补充

四、websocket(非http协议)请求:

0、首先需要安装python的websocket模块:pip install websocket-client

xxxxxxx@localhost  /yyyyyy/work/2_locust  sudo pip install websocket-client
......
Successfully installed websocket-client-0.56.0

1、为了方便测试,自己实现一个websocket后端服务(网上有很多,可以自己搜一下)—注意:这个ws服务最好在自己的linux虚拟机上启动,否则用k8s跑的时候可能无法连接你本机的ws服务

xxxxxxx@localhost  /yyyyyy/work/2_locust  vim websocket_server_demo.py
## pip install bottle_websocket
## pip install bottle
from bottle import get, run, template  
from bottle.ext.websocket import GeventWebSocketServer  
from bottle.ext.websocket import websocket  
import gevent  

users = set()  

@get('/')  
def index():  
    return template('index')  

@get('/websocket', apply=[websocket])  
def chat(ws):  
    users.add(ws)  
    while True:  
        msg = ws.receive()  
        if msg is not None:  
            for u in users:  
                print type(u)  
                u.send(msg)  
                print u,msg  
        else: break  
    users.remove(ws)  

run(host='127.0.0.1', port=9529, server=GeventWebSocketServer) 


# 启动ws服务
xxxxxxx@localhost  /yyyyyy/work/2_locust  python websocket_server_demo.py
Bottle v0.12.16 server starting up (using GeventWebSocketServer())...
Listening on http://127.0.0.1:9529/
Hit Ctrl-C to quit.
.......用下面2中的脚本请求的话,输出如下信息....
<class 'geventwebsocket.websocket.WebSocket'>
<geventwebsocket.websocket.WebSocket object at 0x101005fa0> 11111111111111111111

2、编写websocket测试脚本:

# 编写locustfile.py文件(文件名需要是locustfile.py这个,因为locust本地运行默认找这个文件,否则会报错没有locustfile.py文件)
xxxxxxx@localhost  /yyyyyy/work/locust  vim locustfile.py    ---demo如下:from locust import Locust, events, task, TaskSet
from locust import Locust, events, task, TaskSet
import websocket
import xmlrpclib
import time

host = "127.0.0.1"
# host = "xx.xx.101.52"
port = 9529
base_url = "ws://" + host + ":" + str(port) + "/websocket"

class WebSocketClient(object):
    def __init__(self, host, port):
        self.host = host
        self.port = port
        self.ws = websocket.WebSocket()

    def connect(self, burl):
        start_time = time.time()
        try: 
            self.conn  = self.ws.connect(url=burl)
        except websocket.WebSocketTimeoutException as e:
            total_time  = int((time.time() - start_time) * 1000)
            # events.request_failure.fire(request_type="websockt", name="baseurl", response_time=total_time, exception=e)
        else:
            total_time = int((time.time() - start_time) * 1000)
            # events.request_success.fire(request_type="websockt", name="baseurl", response_time=total_time, response_length=0) 
        return self.conn 

    def recv(self): 
        return self.ws.recv() 

    def send(self, msg): 
        self.ws.send(msg)


class WebSocketLocust(Locust):
    def __init__(self, *args, **kwargs):
        super(WebSocketLocust, self).__init__(*args, **kwargs)
        self.client = WebSocketClient(host, port)

class UserBehavior(TaskSet):

    @task(1)
    def send(self):
        try:
            self.client.connect(base_url)
            start_time = time.time()
            self.client.send('11111111111111111111')
            result = self.client.recv()
        except xmlrpclib.Fault as e:
            total_time = int((time.time() - start_time) * 1000)
            events.request_failure.fire(request_type="websockt", name="send", response_time=total_time, exception=e)
        else:
            total_time = int((time.time() - start_time) * 1000)
            events.request_success.fire(request_type="websockt", name="send", response_time=total_time,
                                        response_length=0)

class WebsiteUser(WebSocketLocust):
    min_wait = 1000
    max_wait = 2000
    task_set = UserBehavior

3、本地调试自己的压测脚本是否ok

# no-web模式先看看---1s1个跑5s看看
 xxxxxxx@localhost  /yyyyyy/work/2_locust  locust -f locustfile.py --no-web -c 1 -r 1 --run-time 5s
[2019-04-22 17:19:46,585] localhost/INFO/locust.main: Run time limit set to 5 seconds
[2019-04-22 17:19:46,585] localhost/INFO/locust.main: Starting Locust 0.11.1
[2019-04-22 17:19:46,585] localhost/INFO/locust.runners: Hatching and swarming 1 clients at the rate 1 clients/s...
 Name                                                          # reqs      # fails     Avg     Min     Max  |  Median   req/s
--------------------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------------------------------
 Total                                                              0     0(0.00%)                                       0.00

[2019-04-22 17:19:47,587] localhost/INFO/locust.runners: All locusts hatched: WebsiteUser: 1
 Name                                                          # reqs      # fails     Avg     Min     Max  |  Median   req/s
--------------------------------------------------------------------------------------------------------------------------------------------
 websockt baseurl                                                   2     0(0.00%)      13       3      24  |       3    0.00
 websockt send                                                      2     0(0.00%)       1       0       3  |       0    0.00
--------------------------------------------------------------------------------------------------------------------------------------------
 Total                                                              4     0(0.00%)                                       0.00

 Name                                                          # reqs      # fails     Avg     Min     Max  |  Median   req/s
--------------------------------------------------------------------------------------------------------------------------------------------
 websockt baseurl                                                   3     0(0.00%)      10       3      24  |       3    1.00
 websockt send                                                      3     0(0.00%)       1       0       3  |       0    1.00
--------------------------------------------------------------------------------------------------------------------------------------------
 Total                                                              6     0(0.00%)                                       2.00

[2019-04-22 17:19:51,590] localhost/INFO/locust.main: Time limit reached. Stopping Locust.
[2019-04-22 17:19:51,591] localhost/INFO/locust.main: Shutting down (exit code 0), bye.
[2019-04-22 17:19:51,591] localhost/INFO/locust.main: Cleaning up runner...
[2019-04-22 17:19:51,591] localhost/INFO/locust.main: Running teardowns...
 Name                                                          # reqs      # fails     Avg     Min     Max  |  Median   req/s
--------------------------------------------------------------------------------------------------------------------------------------------
 websockt baseurl                                                   4     0(0.00%)       8       3      24  |       3    0.67
 websockt send                                                      4     0(0.00%)       0       0       3  |       0    0.67
--------------------------------------------------------------------------------------------------------------------------------------------
 Total                                                              8     0(0.00%)                                       1.33

Percentage of the requests completed within given times
 Name                                                           # reqs    50%    66%    75%    80%    90%    95%    98%    99%   100%
--------------------------------------------------------------------------------------------------------------------------------------------
 websockt baseurl                                                    4      3      3     24     24     24     24     24     24     24
 websockt send                                                       4      0      0      3      3      3      3      3      3      3
--------------------------------------------------------------------------------------------------------------------------------------------
 Total                                                               8      3      3      3      3     24     24     24     24     24


# 再界面化看看
xxxxxxx@localhost  /yyyyyy/work/2_locust  locust -f locustfile.py
[2019-04-22 17:00:34,783] localhost/INFO/locust.main: Starting web monitor at *:8089
[2019-04-22 17:00:34,783] localhost/INFO/locust.main: Starting Locust 0.11.1

4、接3中的界面化部分
在这里插入图片描述

xxxxxxx@localhost  /yyyyyy/work/2_locust  locust -f locustfile.py
[2019-04-22 17:00:34,783] localhost/INFO/locust.main: Starting web monitor at *:8089
[2019-04-22 17:00:34,783] localhost/INFO/locust.main: Starting Locust 0.11.1
[2019-04-22 17:00:45,854] localhost/INFO/locust.runners: Hatching and swarming 1 clients at the rate 1 clients/s...
[2019-04-22 17:00:46,857] localhost/INFO/locust.runners: All locusts hatched: WebsiteUser: 1

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

发布了77 篇原创文章 · 获赞 55 · 访问量 13万+

猜你喜欢

转载自blog.csdn.net/langhailove_2008/article/details/89496337