PFLB

PFLB logo

k6的用户手册,一个用于负载利记手机app的开源工具

What is k6? Who is it for? K6是一个流行的开源工具,用于为工程团队构建负载利记手机app. Born as a startup, k6于2021年被Grafana Labs收购, 也许是因为它与大量第三方工具的集成能力. In this article, we will lay out our experience of working with k6 and our opinion on how to make the best of using it.

Table of Contents

希望避免性能利记手机app错误?

Just hand it over to us. 没有比PFLB更适合QA解决方案的地方了.

Advantages of k6

  • K6的系统资源消耗最小,性能高.
  • With k6, 您将能够执行不同类型的负载利记手机app, for example, maximum search tests, stress tests, or reliability tests.
  • 性能监视:k6为自动化性能利记手机app提供了极好的机会. 您可以以较轻的负载运行利记手机app,以持续监视系统的性能.

Limitations of k6

  • K6显示网页的方式与浏览器不同. 这意味着使用浏览器api的库将不兼容. 这种实现大大减少了系统资源的消耗, though, 哪种工具更高效. 同时,k6可以用于网站和应用程序的负载利记手机app. 可以从记录的用户会话创建脚本.
  • JavaScript通常不适合非常高的负载. To achieve maximum performance, the tool itself is written in Go with a built-in JavaScript runtime environment that allows you to easily create test scripts.

Starting load testing with k6

在k6中,产生负载的函数是这样的:

export default function() {

}

你可以在下面一个简单的脚本中看到它的使用:

import http from ‘k6/http’;

import { sleep } from ‘k6’;

export default function () {

http.get(‘http://test.k6.io’);

sleep(1);

}

And this is how you launch k6:

k6 run script.js

现在让利记手机app添加虚拟用户(vu)并设置利记手机app的持续时间:

K6运行-vus 10 -duration 30s脚本.js

你可以在脚本中这样做:

stages: [

{持续时间:' 2m ',目标:1000},

{duration: ' 30m ', target: 1000},

{duration: ' 30s ', target: 1500},

{持续时间:' 30m ',目标:1500}

],

Or use this code:

export let options = {

vus: 10,

duration: ’30s’,

};

User manual for k6 01

想知道一家领先的医疗保健公司如何提高网站性能x30?

在利记手机app的帮助下,他们在一周内达到了他们的商业目标

网站性能的最佳实践案例研究

负载利记手机app中的k6虚拟用户是什么?

k6 works with the concept of virtual users (VUs) that run scripts – they are essentially parallel while (true) loops. 脚本以ES6模块(JS规范)的形式使用JavaScript编写。, 这允许您将大型利记手机app分割成较小的部分或创建可重用的部分.

脚本应该至少包含一个默认函数——它定义了vu的入口点.

export default function () {

// vu code: do things here…

}

The code inside the default function is called “VU code” and is repeated over and over while the test is running. 它外面的代码被称为“初始化代码”,对每个VU只运行一次.

VU代码可以执行HTTP请求, generate metrics, and generally do everything you would expect from a load test – with a few important exceptions: you cannot upload anything from your local file system or import any other modules. 所有这些都需要从初始化代码中完成.

You can use options.在负载利记手机app期间更改vu的数量.

import http from ‘k6/http’;

从' k6 '导入{check, sleep};

export const options = {

stages: [

{duration: ' 30s ', target: 20},

{duration: ' 1m30s ', target: 10},

{duration: ' 20s ', target: 0},

],

};

export default function () {

const res = http.get(‘http://httpbin.org/’);

check(res, { ‘status was 200’: (r) => r.status == 200 });

sleep(1);

}

这也可以通过使用更高级的配置来完成 scenarios and the ramping-vus executor.

What are test scenarios in k6?

场景为vu和迭代提供了更好的调优机会. 多个场景可以在一个脚本中工作, 每一个都可以独立执行不同的JavaScript函数. 每个场景都可以使用自己数量的vu和迭代模式. 场景可以配置为按顺序或同时运行.

export const options = {

scenarios: {

example_scenario: {

// name of the executor to use

executor: ‘shared-iterations’,

//常见场景配置

startTime: ’10s’,

gracefulStop: ‘5s’,

{EXAMPLEVAR: ' testing '},

标签:{example_tag: ' testing '},

//特定于执行器的配置

vus: 10,

iterations: 200,

maxDuration: ’10s’,

},

another_scenario: {

/*…*/

},

},

};

User manual for k6 02

没有负载利记手机app经验?

Leave it to us. 利记手机app会一劳永逸地安排好一切.
给利记手机app写信,了解利记手机app的团队能为您做些什么.

Types of executors in k6

执行程序是k6执行引擎的主力. 每个项目都以不同的方式安排vu和迭代, 您将根据您想要建模的流量类型选择一个来利记手机app您的利记手机.

k6中的执行器类型如下:

Name

Value

Description

Shared iterations

shared-iterations

固定数量的迭代“分布”在几个vu之间.

Per VU iterations

per-vu-iterations

每个VU执行精确的迭代次数.

Constant VUs

constant-vus

A fixed number of VUs execute the maximum possible number of iterations within a specified time interval.

Ramping VUs

ramping-vus

可变数量的vu在给定的时间间隔内执行迭代的最大次数.

Constant Arrival Rate

constant-arrival-rate

在指定的时间段内执行固定数量的迭代.

Ramping Arrival Rate

ramping-arrival-rate

在指定的时间段内执行可变数量的迭代.

Externally Controlled

externally-controlled

使用k6的REST API或命令行接口(CLI)进行运行时管理和扩展.

还有一些常用选项可用于执行程序:

Option

Type

Description

default

executor(required)

string

从可能值列表中获取执行程序的名称.

-

startTime

string

从负载利记手机app开始开始的倒计时,之后场景应该开始执行.

"0s"

gracefulStop

string

在强制停止迭代之前等待迭代完成执行的时间.

"30s"

exec

string

要执行的导出JS函数的名称.

"default"

env

object

特定于此场景的环境变量.

{}

tags

object

Tags specific to this scenario.

{}

Shared iterations

固定数量的迭代“分布”在多个vu之间, 利记手机app在所有迭代完成后结束. 迭代的分布是不均匀的,一些vu将比其他vu执行更多的迭代.

Option

Type

Description

default

vus

integer

并发运行的vu数量.

1

iterations

integer

所有vu执行的场景迭代的总数.

1

maxDuration

string

场景在被迫停止之前的最长持续时间(不包括gracefulStop).

"10m"

Use Shared iterations if you want a certain number of VUs to perform a fixed total number of iterations, 一个VU执行的迭代次数并不重要.

In the following example, 利记手机app将执行总共200个迭代, distributed among 10 VUs, 最长持续时间为10秒:

import http from ‘k6/http’;

export const options = {

discardResponseBodies: true,

scenarios: {

contacts: {

executor: ‘shared-iterations’,

vus: 10,

iterations: 200,

maxDuration: ’10s’,

},

},

};

export default function () {

http.get(‘http://test.k6.io/contacts.php’);

}

import http from ‘k6/http’;

export const options = {

discardResponseBodies: true,

scenarios: {

contacts: {

executor: ‘shared-

iterations’,

vus: 10,

iterations: 200,

maxDuration: ’10s’,

},

},

};

export default function () {

http.get(‘http://test.k6.io/

contacts.php’);

}

Per VU iterations

每个VU执行精确的迭代次数. 执行的迭代总数将等于vus*迭代.

Option

Type

Description

default

vus

integer

同时运行的vu数量

1

iterations

integer

每个VU执行的迭代次数.

1

maxDuration

string

场景在被迫停止之前的最长持续时间(不包括gracefulStop).

"10m"

如果您需要一定数量的vu来执行一定数量的迭代,则使用此执行器. 当您有固定的利记手机app数据集,想要在vu之间分割时,这可能很有用.

In the following example, 10个vu每个执行20次迭代, 总共200次迭代,最长持续时间为1小时30分钟:

import http from ‘k6/http’;

export const options = {

discardResponseBodies: true,

scenarios: {

contacts: {

executor: ‘per-vu-iterations’,

vus: 10,

iterations: 20,

maxDuration: ‘1h30m’,

},

},

};

export default function () {

http.get(‘http://test.k6.io/contacts.php’);

}

import http from ‘k6/http’;

export const options = {

discardResponseBodies: true,

scenarios: {

contacts: {

executor: ‘per-vu-

iterations’,

vus: 10,

iterations: 20,

maxDuration: ‘1h30m’,

},

},

};

export default function () {

http.get(‘http://test.k6.io/

contacts.php’);

}

Constant VUs

A fixed number of VUs performs the maximum possible number of iterations within a specified time interval.

Option

Type

Description

default

duration(required)

string

场景的总持续时间(不包括gracefulStop).

-

vus

integer

并发运行的vu数量.

1

如果您需要特定数量的vu在特定时间内工作,请使用此执行程序.

在本例中,10个vu将连续工作45分钟:

import http from ‘k6/http’;

import { sleep } from ‘k6’;

export const options = {

discardResponseBodies: true,

scenarios: {

my_awesome_api_test: {

executor: ‘constant-vus’,

vus: 10,

duration: ’45m’,

},

},

};

export default function () {

http.get(‘http://test-api.k6.io/’);

sleep(Math.random() * 3);

}

Ramping VUs

可变数量的vu在给定的时间间隔内执行最大次数的迭代.

Option

Type

Description

default

stages(required)

array

一个对象数组,定义要增加或减少的vu的目标数量.

[ ]

startVUs

integer

利记手机app开始时要运行的vu的数量.

1

gracefulRampDown

string

The time to wait for the completion of an already started iteration before stopping it during a ramp down.

"30s"

如果您需要在特定时间段内增加或减少vu的数量,请使用此执行器.

In this example, we will run a two-step test with an increase from 0 to 100 VUs in 5 seconds and back to 0 VUs in 5 seconds:

import http from ‘k6/http’;

export const options = {

discardResponseBodies: true,

scenarios: {

contacts: {

executor: ‘ramping-vus’,

startVUs: 0,

stages: [

{持续时间:' 5s ',目标:100},

{ duration: ‘5s’, target: 0 },

],

gracefulRampDown: ‘0s’,

},

},

};

export default function () {

http.get(‘http://test.k6.io/contacts.php’);

}

import http from ‘k6/http’;

export const options = {

discardResponseBodies: true,

scenarios: {

contacts: {

executor: ‘ramping-vus’,

startVUs: 0,

stages: [

{持续时间:' 5s ',目标:100},

{ duration: ‘5s’, target: 0 },

],

gracefulRampDown: ‘0s’,

},

},

};

export default function () {

http.get(‘http://test.k6.io/

contacts.php’);

}

Constant arrival rate

在一定的时间内执行固定数量的迭代. 因为迭代执行时间可以变化, for example, 由于系统在利记手机app时变慢, 这个执行程序将试图通过运行额外的vu来弥补这一点, 包括可能在利记手机app中间初始化更多, 维护已配置的迭代速率.

Option

Type

Description

default

duration(required)

string

场景的总持续时间(不包括gracefulStop)

-

rate(required)

integer

每个指定周期要执行的迭代次数(TimeUnit)

-

preAllocatedVUs(required)

integer

在开始利记手机app之前必须预先分配的vu数量

-

timeUnit

string

应用速率值的时间段

"1s"

maxVUs

integer

利记手机app期间允许的vu的最大数量

-

Use this executor to maintain a constant number of requests without affecting the performance of the system under test.

In this example, 利记手机app将在一分钟内保持每秒200个请求的恒定强度, 这将允许k6动态调度多达100个vu:

import http from ‘k6/http’;

export const options = {

discardResponseBodies: true,

scenarios: {

contacts: {

遗嘱执行人:“constant-arrival-rate”,

rate: 200, // 200 RPS,因为timeUnit是默认的1

duration: ‘1m’,

preAllocatedVUs: 50,

maxVUs: 100,

},

},

};

export default function () {

http.get(‘http://test.k6.io/contacts.php’);

}

import http from ‘k6/http’;

export const options = {

discardResponseBodies: true,

scenarios: {

contacts: {

executor: ‘constant-arrival-

rate’,

rate: 200, // 200 RPS, since

timeUnit is the default 1s

duration: ‘1m’,

preAllocatedVUs: 50,

maxVUs: 100,

},

},

};

export default function () {

http.get(‘http://test.k6.io/

contacts.php’);

}

Ramping arrival rate

在一定的时间内执行的迭代次数是可变的. k6将尝试动态改变vu的数量,以实现给定的迭代频率.

Option

Type

Description

default

stages(required)

array

一个对象数组,指示要增加或减少的迭代的目标次数. 

[ ]

preAllocatedVUs(required)

integer

在开始利记手机app之前必须预先分配的vu数量.

-

startRate

integer

为每个指定周期执行的迭代次数(TimeUnit)

0

timeUnit

string

应用startRate和阶段目标值的时间.

"1s"

maxVUs

integer

利记手机app运行期间允许的vu的最大数量

-

Use this executor, 如果有必要,利记手机app不受被测系统性能的影响, 你想要增加或减少在特定时间段内的迭代次数

In this example, 利记手机app将以每秒不同数量的请求运行一个利记手机app, starting from 50, increasing to 200, 然后在1分钟内回到0:

import http from ‘k6/http’;

export const options = {

discardResponseBodies: true,

scenarios: {

contacts: {

遗嘱执行人:“ramping-arrival-rate”,

startRate: 50,

timeUnit: ‘1s’,

preAllocatedVUs: 50,

maxVUs: 100,

stages: [

{目标:200,持续时间:' 30s '},

{target: 0, duration: ' 30s '},

],

},

},

};

export default function () {

http.get(‘http://test.k6.io/contacts.php’);

}

import http from ‘k6/http’;

export const options = {

discardResponseBodies: true,

scenarios: {

contacts: {

executor: ‘ramping-arrival-

rate’,

startRate: 50,

timeUnit: ‘1s’,

preAllocatedVUs: 50,

maxVUs: 100,

stages: [

{ target: 200, duration:

’30s’ },

{target: 0, duration: ' 30s '},

],

},

},

};

export default function () {

http.get(‘http://test.k6.io/

contacts.php’);

}

Externally controlled

通过k6 REST API或命令行接口在利记手机app期间进行控制和扩展.

Option

Type

Description

default

duration(required)

string

The total duration of the test.

-

vus

integer

并发运行的vu数量.

-

maxVUs

integer

利记手机app期间允许的vu的最大数量

-

如果您想在利记手机app执行期间控制vu的数量,请使用此执行器. 这是k6云中唯一不支持的执行程序, 它只能在k6 (k6 Cloud 是一个基于订阅的利记手机,见利记手机app的文章利记手机app云利记手机的特点”).

In this example, we will run a run-time controlled test starting from 10 VUs to a maximum of 50 and with a total duration of 10 minutes:

import http from ‘k6/http’;

export const options = {

discardResponseBodies: true,

scenarios: {

contacts: {

遗嘱执行人:“外部控制”,

vus: 10,

maxVUs: 50,

duration: ’10m’,

},

},

};

export default function () {

http.get(‘http://test.k6.io/contacts.php’);

}

import http from ‘k6/http’;

export const options = {

discardResponseBodies: true,

scenarios: {

contacts: {

executor: ‘externally-

controlled’,

vus: 10,

maxVUs: 50,

duration: ’10m’,

},

},

};

export default function () {

http.get(‘http://test.k6.io/

contacts.php’);

}

GracefulStop

gracfulstop选项可用于所有类型的执行程序,除了 Externally controlled,并允许用户指定强制中断前的等待时间. 缺省值是30秒.

请注意,尽管示例中利记手机app的总持续时间是10秒, 由于gracfulstop,实际的执行时间是13秒, 这给了VU额外的3秒时间来完成正在执行的迭代. 当前的迭代中有23个没有完成并被中断.

A similar option exists for the ramping-vus 执行者,它是优雅的rampdown. It defines the time during which k6 must wait for any current iterations to complete before the VUs are returned to the pool during the deceleration period defined in stages.

import http from ‘k6/http’;

export const options = {

discardResponseBodies: true,

scenarios: {

contacts: {

executor: ‘constant-vus’,

vus: 100,

duration: ’10s’,

gracefulStop: ‘3s’,

},

},

};

export default function () {

const delay = Math.floor(Math.random() * 5) + 1;

http.get(`http://httpbin.test.k6.io/delay/${delay}`);

}

import http from ‘k6/http’;

export const options = {

discardResponseBodies: true,

scenarios: {

contacts: {

executor: ‘constant-vus’,

vus: 100,

duration: ’10s’,

gracefulStop: ‘3s’,

},

},

};

export default function () {

const delay =

Math.floor(Math.random() * 5)

+ 1;

http.get(`http://httpbin.test.

k6.io/delay/${delay}`);

}

运行这个脚本会得到如下结果:

running (13.0), 000/100 vu, 349个完整迭代和23个中断迭代

✓接触 [======================================] 执行100年的vu 10年代

running (13.0), 000/100 vu, 349个完整迭代和23个中断迭代

contacts ✓ [==================

====================] 100 vu 10s

不想自己运行利记手机app?

没有比PFLB更适合QA解决方案的地方了.
给利记手机app写信,了解利记手机app的团队能为您做些什么.

Metrics in k6

Built-in metrics

Metric name

Type

Description

vus

Gauge

当前活跃的虚拟用户数量

vus_max

Gauge

The maximum possible number of VUs in the test (resources for VUs are allocated in advance to ensure that performance does not suffer when the load level increases)

iterations

Counter

Iteration counter. vu在利记手机app中执行脚本的次数(默认函数).

iteration_duration

Trend

执行一次完整的函数迭代所需要的时间.

dropped_iterations

Counter

The number of iterations that could not be started due to lack of VUs (arrival-rate executors) or lack of time (due to expired maxDuration in iteration-based executors).

data_received

Counter

The amount of data received

data_sent

Counter

The amount of data sent

checks

Rate

Number of successful checks

http_reqs

Counter

k6总共生成了多少HTTP请求.

http_req_blocked

Trend

在发起请求之前,阻塞(等待空闲的TCP连接插槽)所花费的时间. float

http_req_connecting

Trend

与远程主机建立TCP连接所需的时间. float

http_req_tls_handshaking

Trend

与远程主机协商TLS会话所花费的时间

http_req_sending

Trend

将数据发送到远程主机所需的时间. float

http_req_waiting

Trend

等待来自远程主机响应的时间(“第一个字节的时间”,或“TTFB”). float

http_req_receiving

Trend

从远程主机接收响应数据所需的时间. float

http_req_duration

Trend

Total request time. It is equal to

http_re_sending +

http_ru_waiting +

http_ru_receiving (i.e. how long it took the remote server to process the request and respond without the initial DNS lookup/connection time). float

http_req_failed (≥ v0.31)

Rate

根据setResponseCallback的失败请求数.

To make it clear, setResponseCallback is a function that must be executed after another function has completed execution (hence the name). You can use the setResponseCallback function to determine whether the response was successful or failed.

Types of metrics

Counter and Gauge that have a value of zero (0) at the end of the test are an exception: they will NOT be output to the stdout summary.

您可以通过Response获取关于特定请求的信息.timings object:

metric Type

Description

Counter

Counter. Summarizes the values.

Gauge

存储添加到其中的最小值、最大值和最后值的度量.

Rate

显示非零值百分比的一种度量.

Trend

一种度量,允许您计算附加值的统计信息(最小值, maximum, average and percentiles).

  • blocked = http_req_blocked;
  • 连接= http_req_connecting;
  • tls_握手= http_req_tls_握手;
  • sending = http_req_sending;
  • waiting = http_req_waiting;
  • receiving = http_req_receiving;
  • duration = http_req_duration.

import http from ‘k6/http’;

export default function () {

const res = http.get(‘http://httpbin.org’);

console.'响应时间为' + String(res . log.timings.duration) + ‘ ms’);

}

Custom metrics

您还可以创建自己的指标,这些指标将在负载利记手机app结束时显示.

In the example below, 将创建一个名为“wait_time”的趋势类型指标, 在代码中由谁引用 myTrend variable.

import http from ‘k6/http’;

import {Trend} from ' k6/metrics ';

const myTrend = new趋势(' waiting_time ');

export default function () {

const r = http.get(‘http://httpbin.org’);

myTrend.add(r.timings.waiting);

console.log(myTrend.name); // waiting_time

}

Reporting results in k6

Default results report in k6

By default, at the end of each load test, K6将带有利记手机app结果概述的总结报告打印到标准输出. 它包括所有内置和可配置指标和设置的聚合值, thresholds, groups, and checks. If this is not enough, K6还支持将指标传输到一个或多个外部工具, such as InfluxDB, Kafka, StatsD, etc. The raw results can also be sent to a cloud service and exported as a CSV or JSON file for later processing.

User manual for k6 1

Starting from k6 v0.30.0,您可以完全自定义输出并将其重定向到文件.

The no-summary indicator disables the reports. handleSummary () callback allows you to fully customize the summary at the end of the test and export the summary report data in any desired format, such as JSON, CSV, XML (JUnit / xUnit, etc.), HTML, TXT, etc.

Standard output includes min., med.、最大值和百分位数. 在标准输出中,它们是这样打印的:

http_req_duration……….: avg=143.14ms min=112.87ms med=136.03ms max=1.18s p(90)=164.2ms p(95)=177.75ms

You can use the summaryTrendStats 选项更改统计信息输出. 还可以使用固定的时间单位(秒)配置时间值的显示, 毫秒或微秒)使用 summaryTimeUnit option:

K6 run -summary-trend-stats = " min,avg,med,p(99),p(99).9),max,count " -summary-time-unit =ms脚本.js

K6 run -summary-trend-stats = " min, average,med,p(99), p(99.9),max,count " -summary-time-unit=ms脚本.js

在k6中导出负载利记手机app总结到其他平台

如果利记手机app结束时的标准输出不够, 您可以在其他平台上集成和可视化k6指标. 使用out标志将结果发送到外部输出.

k6 run –out statsd script.js

你也可以通过多次使用out标志向多个输出同时发送指标:

k6 run \

–out json=test.json \

–out influxdb=http://localhost:8086/k6

k6 run \

–out json=test.json \

–out influxdb= http://localhost:8086/k6

目前可用的内置输出包括Amazon CloudWatch, Apache Kafka, Cloud, CSV, Datadog, Grafana Cloud / Prometheus, InfluxDB, JSON, Netdata, New Relic, Prometheus, StatsD.

handleSummary() callback

In k6 v0.30.0, there is handleSummary(), 一种以JSON格式导出汇总数据的新方法, 还有很多其他的形式, such as CSV, XML, HTML, TXT, etc. 利记手机app建议使用handleSummary()来代替旧的函数, –summary-export.

方法可以完全自定义最终报告 handleSummary() function. K6将在利记手机app结束时调用它. 除了在利记手机app结束时配置摘要之外, 您可以将数据转换为各种格式并将它们保存到文件中, 或者将生成的报告发送到远程利记手机器.

Checks

检查不会停止利记手机app执行. Instead, 它们保存检查的结果(true/false),并允许您继续执行脚本. 您可以在下面的例子中看到多重检查.

import { check } from ‘k6’;

import http from ‘k6/http’;

export default function () {

const res = http.get(‘http://test.k6.io/’);

check(res, {

‘is status 200’: (r) => r.status === 200,

‘body size is 11,105 bytes’: (r) => r.body.length == 11105,

});

}

Thresholds

Thresholds are a pass/fail criteria used to specify the performance expectations of the system under test. 阈值分析性能指标并确定最终利记手机app结果(通过/失败). 其中一些例子可能包括:

  • 文本中的错误数不超过1%.
  • 95%的请求的响应时间应该小于200毫秒.
  • 99%的请求的响应时间应该小于400毫秒.

The following example contains a scenario that defines two thresholds: error rate (http_read_failed metric) and 95 percentile response durations (http_req_duration metric).

import http from ‘k6/http’;

export const options = {

thresholds: {

http_req_failed: [‘rate<0.01 '], // HTTP错误应该小于1%

http_req_duration: [‘p(95)<200’], // 95% of requests should be below 200ms

},

};

export default function () {

http.get(‘http://test-api.k6.io/public/crocodiles/1/’);

}

如果超过任何阈值, 在度量名称旁边的一个绿色小勾将变成一个红十字, k6会生成一个非零的退出码.

✓ http_req_duration…………..: avg=151.06ms min=151.06ms med=151.06ms max=151.06ms p(90)=151.06ms p(95)=151.06ms

{expected_response:true}: avg=151.06ms min=151.06ms med=151.06ms max=151.06ms p(90)=151.06ms p(95)=151.06ms

✓ http_req_failed…………….: 0.00% ✓ 0 ✗ 1

Groups

组用于根据公共逻辑组织场景. Groups can be nested. For each group() function, K6生成一个group_duration度量,其中包含组函数的总执行时间. When a tagged resource (checks, queries, 或自定义度量)在组中执行, K6使用当前组名设置标记组.

import { group } from ‘k6’;

export default function () {

组('访问利记手机app页面',函数(){

// …

});

组(“向购物车中添加多个产品”,函数(){

// …

});

组('访问登录页面',函数(){

// …

});

组(' authenticate ',函数(){

// …

});

组(“签出过程”,函数(){

// …

});

}

Tags in k6

标签是对k6对象进行分类的一种简单而有效的方法,可用于后续的结果筛选.

K6提供两种类型的标记:用户定义的标记, 您在编写脚本时添加的那些, and system tags, automatically assigned by k6.

System tags in k6

自动创建的标签列表包括:

tag

Description

proto

使用的协议(例如,HTTP/1).1)

subproto

子协议(由web套接字使用)

status

HTTP状态码(例如200、404等).)

method

the HTTP method name (e.g. GET, POST, etc.) or the RPC method for gRPC

url

URL of the HTTP request

name

HTTP request name

group

the full group path

check

the Check name

error

包含HTTP之外的错误消息的字符串(例如,网络或DNS错误)

error_code

对不同的错误类型唯一的数字

tls_version

the TLS version

scenario

发出度量的场景的名称

service

gRPC的RPC利记手机名称

Custom tags

自定义标记允许您对k6对象进行分类. 您可以标记以下对象:检查、阈值和查询.

import http from ‘k6/http’;

import {Trend} from ' k6/metrics ';

import { check } from ‘k6’;

const myTrend = new趋势(' my_trend ');

export default function () {

//添加标签请求度量数据

const res = http.get(‘http://httpbin.org/’, {

tags: {

my_tag: “I’m a tag”,

},

});

// Add tag to check

check(res, { ‘status is 200’: (r) => r.status === 200}, {my_tag: " I 'm a tag "});

// Add tag to custom metric

myTrend.add(res.timings.连接,{my_tag: " I 'm a tag "});

}

import http from ‘k6/http’;

import {Trend} from ' k6/metrics ';

import { check } from ‘k6’;

const myTrend = new趋势(' my_trend ');

export default function () {

//添加标签请求度量数据

const res = http.get(‘http://httpbin.org/’, {

tags: {

my_tag: “I’m a tag”,

},

});

// Add tag to check

check(res, { ‘status is 200’: (r) => r.status === 200}, {my_tag: " I 'm a tag "});

// Add tag to custom metric

myTrend.add(res.timings. 连接,{my_tag: " I 'm a tag "});

}

寻找性能和负载利记手机app提供者?

Drop us a line. 很可能,利记手机app在之前的300个项目中已经处理过类似您的问题.

How to record a script in k6?

要利记手机app网站或web应用程序,可以在浏览器中记录用户会话. To do this, use k6 Browser Recorder, available in Chrome Webstore.

Open the recorder by clicking the “k6 Browser Recorder” icon in the upper right corner of the browser window, 点击“开始录音”并在当前浏览器选项卡中开始录音.

要停止录制,请点击“停止”. 您将被带到k6浏览器记录器 application page to view the test scenario. 您需要创建一个用户帐户. 作为记录浏览器会话的结果,您得到的利记手机app脚本是JavaScript. 你可以在应用程序的脚本编辑器中编辑这个脚本. 这允许您在必要时创建更复杂的利记手机app场景. 例如,您可以使用参数化的登录数据.

User manual for k6 2

使用k6中的内置命令对利记手机app进行动态控制

The built-in k6 commands “pause”, “resume”, “scale”, “stats” and “status” 可以用来控制正在运行的利记手机app的行为吗. Basically, what you do is start a k6 test in one terminal window and then from another terminal window (or of course it could be programmatic execution – a batch job or whatnot) you issue k6 commands to control the running test. Here are some examples:

Status:

User manual for k6 3

Pause:

User manual for k6 4

Resume:

User manual for k6 5

Scale:

这个命令允许您在利记手机app期间增加或减少负载级别(vu的数量).

User manual for k6 6

What is vus-max in k6?

VU参数有vus和vus-max. 第一个是利记手机app中当前活动vu的实际数量. 它是用来提高或降低负载级别的. 第二个值(vus-max)是当前值 limit 你可以激活多少vu. 如果你尝试将vus扩展到一个高于vus-max的级别,会发生这样的情况:

User manual for k6 7

The vus-max parameter exists because creating new VUs is an expensive operation: you need to reserve a lot of memory and initialize a lot of data structures. Initializing a large number of new VUs during the test execution may negatively affect the load test itself (halting it for a while or affecting the reliability of the measurement).

如果在利记手机app期间任意更改vu编号很简单, users might encounter problems when starting the test with a small number of VUs and then scaling it to a significant increase. 所以k6试图让用户不断意识到这个问题, and still provide flexibility, 是否需要在设置vus参数之前设置vus-max参数. It also gives users more control; Increasing vus-max means that k6 will immediately start allocating memory etc for the extra VUs.

用户可以决定k6什么时候应该在分配和配置上花费CPU资源, and when it should use the CPU to actually generate load testing traffic and perform accurate measurements.

这里有一个例子,利记手机app在利记手机app期间将VUs -max从10增加到50 vu, 一般不推荐哪种, 但在低负载水平下,没有明显的减速:

User manual for k6 8

How to configure vus-max in k6?

最好的方法是设置vus-max一次, on startup, 并将它设置得足够高,这样您就不需要在运行时增加它. The second best thing, 如果确实需要在运行时增加vus-max, is to pause the test, increase vus-max, and then resume again. 这样,当k6忙于创建新的vu时,就不会发生任何重要的事情.

You can also do what we did in the screenshot above and just change vus-max while the test is running, without pausing it first. 如果您这样做,您只需为不稳定的利记手机app结果或利记手机app流量中的临时停顿做好准备.

没有负载利记手机app经验?

Leave it to us. 利记手机app会一劳永逸地安排好一切.
给利记手机app写信,了解利记手机app的团队能为您做些什么.

如何远程控制k6中的利记手机app?

在一个终端窗口中开始k6, 从同一台机器的另一个窗口控制它可能看起来不是很“遥远”, 但是您可以从任何地方控制k6实例, 只要你能和正在运行的机器通信就行.

在幕后发生的事情是,原来的k6进程启动一个HTTP利记手机器, exposing a REST API on localhost:6565. 有了这个API,你可以看到和控制不同的执行方面,如vu的数量, Max VUs, pause or resume the test, list groups, 设置和获取设置数据等等.

By default, k6 scale and the other commands will assume you want to talk to a k6 process that is running its API server on localhost:6565, but you can use the -a/–address 命令行选项,为API利记手机器指定绑定地址/端口.g. k6 run –address 1.2.3.4:5678 –paused myscript.js)和你想控制的k6的位置(k6 scale –address 1.2.3.4:5678 –vus 50).

Get Status

curl -X GET \

http://localhost: 6565 / v1 /状态\

-H ' Content-Type: application/json '

Update Status

curl -X PATCH \

http://localhost: 6565 / v1 /状态\

-H ' Content-Type: application/json ' \

-d ‘{

“data”: {

“attributes”: {

“paused”: true,

“vus”: 1,

“vus-max”: 1

},

“id”: “default”,

“type”: “status”

}

}’

PATCH allows you to pause/resume the current test and set the number of vus and vus-max during the test.

List Metrics

curl -X GET \

http://localhost:6565/v1/metrics \

-H ' Content-Type: application/json '

这个端点将为您提供当前时间内的所有指标. 你可以在上面看到更多关于所有可用指标以及如何创建新指标的细节.

Get Metric

当前时刻特定度量的详细信息.

curl -X GET \

http://localhost: 6565 / v1 /标准/ http_req_receiving \

-H ' Content-Type: application/json '

curl -X GET \

http://localhost:6565/v1/ metrics/http_req_receiving \

-H ' Content-Type: application/json '

List Groups

列表组返回利记手机app中可用的所有组.

curl -X GET \

http://localhost: 6565 / v1 /组\

-H ' Content-Type: application/json '

Get Group

这个端点返回一个具有指定ID的组.

curl -X GET \http://localhost:6565/v1/group/

b0470a9324a4ae563b04e9ac49fbc9cf \

-H ' Content-Type: application/json '

curl -X GET \

http://localhost:6565/v1/group /b0470a9324a4ae563b04e9ac 49fbc9cf \

-H ' Content-Type: application/json '

Get Setup Data

This endpoint 返回JSON编码的当前设置.

curl -X GET \

http://localhost: 6565 / v1 /设置\

-H ' Content-Type: application/json '

Run Setup

这个端点执行安装步骤并返回结果.

curl -X POST \

http://localhost: 6565 / v1 /设置\

-H ' Content-Type: application/json '

Update Setup

该指标分析JSON请求的主体,并将结果设置为当前设置.

curl -X PUT \

http://localhost: 6565 / v1 /设置\

-H ' Content-Type: application/json ' \

-d ‘{

“data”: {

“attributes”: {

“data”: {

“a”: 1,

“b”: 2

}

},

“id”: “default”,

“type”: “setupData”

}

}’

Stop Test

curl -X PATCH \

http://localhost: 6565 / v1 /状态\

-H ' Content-Type: application/json ' \

-d ‘{

“data”: {

“type”: “status”,

“id”: “default”,

“attributes”: {

“stopped”: true

}

}

}’

Conclusions

您可以将k6与其他在线性能利记手机app工具进行比较 parameterized comparison before you make up your mind. 每种工具都有其优点和缺点, so it’s better to invest time in making a well-considered decision rather than try each and every tool out there. 利记手机app的400多名工程师已经成功完成了300多件 performance and load testing projects for businesses of different scales, so don’t hesitate to ask for advice in case you need it. We’ll be there for you!

Have a project in mind?

自2008年以来,利记手机app一直致力于性能利记手机app项目.

给利记手机app写信,了解利记手机app的团队能为您做些什么.

vertical divider
Clutch badge orig
2019年欧洲利记手机app奖徽章
Techreviewer 2022 badge orig
CTA performance testing