Locust 官方文档 6:使用更快的 HTTP 客户端提高 Locust 性能
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Locust 官方文档 6:使用更快的 HTTP 客户端提高 Locust 性能相关的知识,希望对你有一定的参考价值。
参考技术ALocust’s default HTTP client uses python-requests .
Locust 默认的 HTTP 客户端使用 python-requests .
The reason for this is that requests is a very well-maintained python package, that provides a really nice API, that many python developers are familiar with.
原因是 requests 库是一个维护良好的 python 程序库,它提供了许多 python 开发人员都熟悉的优雅的 API。
Therefore, in many cases, we recommend that you use the default HttpUser which uses requests.
因此,在很多案例中,我们推荐使用默认的 HttpUser 类,它使用的是 requests 库实现的。
However, if you’re planning to run really large scale tests, Locust comes with an alternative HTTP client, FastHttpUser which uses geventhttpclient instead of requests.
然而,如果你打算运行真正的大规模负载测试,那么 Locust 附带了一个备用 HTTP 客户端 FastHttpUser ,它使用的是 geventhttpclient 。
This client is significantly faster, and we’ve seen 5x-6x performance increases for making HTTP-requests.
使用 geventhttpclient 客户端的速度能获得明显提高,我们发现 HTTP 请求的性能提高了 5 到 6 倍。
This does not necessarily mean that the number of users one can simulate per CPU core will automatically increase 5x-6x, since it also depends on what else the load testing script does.
这并不一定意味着每个 CPU 内核可以模拟的用户数量会自动增加 5 到 6 倍,因为这还取决于负载测试脚本的其他功能(如果测试脚本中有大量处理数据等其他逻辑,也会影响 Locust 的性能)。
However, if your locust scripts are spending most of their CPU time in making HTTP-requests, you are likely to see significant performance gains.
但是,如果 Locust 脚本花费大量的 CPU 时间进行 HTTP 请求,则可能会看到明显的性能提升。
Subclass FastHttpUser instead of HttpUser:
自定义的 User 类 直接继承 FastHttpUser 代替 HttpUser。
Note
Because FastHttpUser uses a different client implementation with a slightly different API, it may not always work as a drop-in replacement for HttpUser.
FastHttpUser uses a different HTTP client (geventhttpclient) compared to HttpUser (python-requests). It’s significantly faster, but not as capable.
与 HttpUser(python requests)相比,FastHttpUser 使用不同的 HTTP 客户端(gevent http client)。它的速度要快得多,但功能没有 HttpUser 强大。
The behaviour of this user is defined by it’s tasks.
该用户的行为由其任务定义。
Tasks can be declared either directly on the class by using the @task decorator on the methods, or by setting the tasks attribute .
可以使用 @task 装饰器标识任务,或者用 tasks 属性来指定任务。
This class creates a client attribute on instantiation which is an HTTP client with support for keeping a user session between requests.
此类在实例化时创建一个 client 属性,该属性是一个 HTTP client,支持在请求之间保持用户会话。
Parameter passed to FastHttpSession
连接超时时间参数
Parameter passed to FastHttpSession. Default True, meaning no SSL verification.
默认值为 True,表示不进行 SSL 验证。
Parameter passed to FastHttpSession. Default 5, meaning 4 redirects.
运行最大的重定向次数。默认值 5,表示 4 次重定向
Parameter passed to FastHttpSession. Default 1, meaning zero retries.
最大重试次数,默认为 1,表示不重试
Parameter passed to FastHttpSession
网络超时时间
Sends a HEAD request
Sends a OPTIONS request
Sends a POST request
Sends a POST request
Sends a PUT request
Send and HTTP request
Returns locust.contrib.fasthttp.FastResponse object.
Parameters:
method – method for the new Request object.
path – Path that will be concatenated with the base host URL that has been specified. Can also be a full URL, in which case the full URL will be requested, and the base host is ignored.
name – (optional) An argument that can be specified to use as label in Locust’s statistics instead of the URL path. This can be used to group different URL’s that are requested into a single entry in Locust’s statistics.
catch_response – (optional) Boolean argument that, if set, can be used to make a request return a context manager to work as argument to a with statement. This will allow the request to be marked as a fail based on the content of the response, even if the response code is ok (2xx). The opposite also works, one can use catch_response to catch a request and then mark it as successful even if the response code was not (i.e 500 or 404).
data – (optional) String/bytes to send in the body of the request
. json – (optional) Dictionary to send in the body of the request. Automatically sets Content-Type and Accept headers to “application/json”. Only used if data is not set.
headers – (optional) Dictionary of HTTP Headers to send with the request.
auth – (optional) Auth (username, password) tuple to enable Basic HTTP Auth.
stream – (optional) If set to true the response body will not be consumed immediately and can instead be consumed by accessing the stream attribute on the Response object. Another side effect of setting stream to True is that the time for downloading the response content will not be accounted for in the request time that is reported by Locust.
Unzips if necessary and buffers the received body. Careful with large files!
Dict like object containing the response headers
Returns the text content of the response as a decoded string
Next Previous
性能工具之locust工具get与post请求
最近在学习 locust 性能工具,发现locust性能工具脚本需要python基础才能写脚本,但是对于性能测试人员来说 python 是基本功夫。
在 locust 中get脚本怎么写,为了方便直接在代码运行调试,采用关闭web模式,通过参考官方文档自己实验get/post代码,参考代码如:
def get_7dTest(self):
# 定义请求头
header = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36"}
response = self.client.get("/7d/", headers=header, verify=False)
# print("Response status code:", response.status_code)
if response.status_code == 200:
print("successful")
# print("Response text:", response.json())
else:
print(\'failure\')
post请求写法如下
# 登陆
@task(1)
def get_login(self):
response = self.client.post("/login", {"userName": "7d", "passWord": "123456"})
print("Response json:", response.json())
结果:
# 结果:
[2021-04-24 21:36:49,495] liwen.local/INFO/locust.main: Run time limit set to 1 seconds
[2021-04-24 21:36:49,495] liwen.local/INFO/locust.main: Starting Locust 1.4.4
[2021-04-24 21:36:49,496] liwen.local/INFO/locust.runners: Spawning 1 users at the rate 1 users/s (0 users already running)...
[2021-04-24 21:36:49,496] liwen.local/INFO/locust.runners: All users spawned: webTestDunShan: 1 (1 total running)
[2021-04-24 21:36:49,496] liwen.local/INFO/root: Terminal was not a tty. Keyboard input disabled
Name # reqs # fails | Avg Min Max Median | req/s failures/s
--------------------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------------------------------
Aggregated 0 0(0.00%) | 0 0 0 0 | 0.00 0.00
Response json: {\'msg\': \'success\', \'code\': 0, \'data\': \'登陆成功\'}
successful
Response json: {\'msg\': \'success\', \'code\': 0, \'data\': \'登陆成功\'}
Response json: {\'msg\': \'success\', \'code\': 0, \'data\': \'登陆成功\'}
Response json: {\'msg\': \'success\', \'code\': 0, \'data\': \'登陆成功\'}
Response json: {\'msg\': \'success\', \'code\': 0, \'data\': \'登陆成功\'}
post请求json请求写法:
@task(1)
def get_login_json(self):
jsonData = {"userName": "7d", "passWord": "123456"}
response = self.client.post("/login/json", json=json.dumps(jsonData))
print("Response json:", response.json())
# 结果
Response json: {\'msg\': \'success\', \'code\': 0, \'data\': \'登陆成功\'}
实验请求资源代码:
public R indexPage() {
HashMap<String, Object> map = new HashMap<>();
map.put("success", "欢迎来到性能实战课堂");
map.put("Data", new Date());
return R.ok().put("data", map);
}
/**
* 登陆
*
* @param memberEntity
* @return
*/
public R login(MemberEntity memberEntity) {
if ("7d".equals(memberEntity.getUserName()) && "123456".equals(memberEntity.getPassWord())) {
return R.ok().put("data", "登陆成功");
}
return R.error().put("data", "用户名或者密码失败");
}
/**
* 登陆
*
* @param requestBody
* @return
*/
public R login_json(
log.info("json数据:{}", requestBody);
Object parse = JSON.parse(requestBody);
MemberEntity memberEntity = JSON.parseObject(parse.toString(), MemberEntity.class);
if ("7d".equals(memberEntity.getUserName()) && "123456".equals(memberEntity.getPassWord())) {
return R.ok().put("data", "登陆成功");
}
return R.error().put("data", "用户名或者密码失败");
}
locust直接在 python 代码调试代码关闭web页面,这样调试很方便,参考如下命令:
os.system("locust -f demoLcou.py --host=http://127.0.0.1:8080 --headless -u 1 -r 1 -t 1s")
# –no-web 表示不使用Web界面运行测试。
# -c 设置虚拟用户数。
# -r 设置每秒启动虚拟用户数。
# -t 设置设置运行时间。
# 结果参考:
[2021-04-24 22:23:59,688] liwen.local/INFO/locust.main: Run time limit set to 1 seconds
[2021-04-24 22:23:59,688] liwen.local/INFO/locust.main: Starting Locust 1.4.4
[2021-04-24 22:23:59,688] liwen.local/INFO/locust.runners: Spawning 1 users at the rate 1 users/s (0 users already running)...
[
2021-04-24 22:23:59,688] liwen.local/INFO/locust.runners: All users spawned: webTestDunShan: 1 (1 total running)
[2021-04-24 22:23:59,689] liwen.local/INFO/root: Terminal was not a tty. Keyboard input disabled
Name # reqs # fails | Avg Min Max Median | req/s failures/s
----------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------
Aggregated 0 0(0.00%) | 0 0 0 0 | 0.00 0.00
successful
Response json: {\'msg\': \'未知异常,请联系管理员\', \'code\': 500, \'data\': \'用户名或者密码失败\'}
。。。。。中间省略。。。。
successful
[2021-04-24 22:24:00,454] liwen.local/INFO/locust.main: Time limit reached. Stopping Locust.
[2021-04-24 22:24:00,454] liwen.local/INFO/locust.runners: Stopping 1 users
[2021-04-24 22:24:00,455] liwen.local/INFO/locust.runners: 1 Users have been stopped, 0 still running
[2021-04-24 22:24:00,455] liwen.local/INFO/locust.main: Running teardowns...
[2021-04-24 22:24:00,455] liwen.local/INFO/locust.main: Shutting down (exit code 0), bye.
[2021-04-24 22:24:00,455] liwen.local/INFO/locust.main: Cleaning up runner...
Name # reqs # fails | Avg Min Max Median | req/s failures/s
--------------------------------------------------------------------------------------------------------------------------------------------
GET / 166 0(0.00%) | 1 1 5 2 | 216.65 0.00
GET /7d/ 89 0(0.00%) | 1 1 12 1 | 116.16 0.00
POST /login 98 0(0.00%) | 1 1 2 1 | 127.90 0.00
POST /login/json 87 0(0.00%) | 1 1 2 2 | 113.55 0.00
--------------------------------------------------------------------------------------------------------------------------------------------
Aggregated 440 0(0.00%) | 1 1 12 2 | 574.26 0.00
Response time percentiles (approximated)
Type Name 50% 66% 75% 80% 90% 95% 98% 99% 99.9% 99.99% 100% # reqs
--------|------------------------------------------------------------|---------|------|------|------|------|------|------|------|------|------|------|------|
GET / 2 2 2 2 2 3 3 5 6 6 6 166
GET /7d/ 1 1 1 1 2 2 2 12 12 12 12 89
POST /login 1 1 1 1 2 2 2 2 2 2 2 98
POST /login/json 2 2 2 2 2 2 2 3 3 3 3 87
--------|------------------------------------------------------------|---------|------|------|------|------|------|------|------|------|------|------|------|
None Aggregated 2 2 2 2 2 2 3 3 12 12 12 440
Process finished with exit code 0
总结:
locust 官方文档还是比较详细,只要慢慢看就能掌握locust工具怎么操作,但是在老师性能工程中,工具只要能发压就行。
以上是关于Locust 官方文档 6:使用更快的 HTTP 客户端提高 Locust 性能的主要内容,如果未能解决你的问题,请参考以下文章