负载测试,压力测试可以衡量服务是否是一个高可用,高性能的服务。负载测试能检验在不同的工作负荷下,服务的硬件消耗和响应,从而得到不同负载情况下的性能指标。
可能说到压力测试,很多人会想到
JMeter
。Apache JMeter是一个Apache项目,可用作负载测试工具,以分析和测量各种服务的性能,重点是Web应用程序。JMeter可用作JDBC数据库连接,FTP,LDAP,Web服务,JMS,HTTP,通用TCP连接和OS本机进程的单元测试工具。下面我们讲另外一个新式的压力测试工具k6
。
K6是一款现代负载测试工具,建立在我们在负载和性能测试行业多年的经验基础上。它提供了一个干净的、可接近的脚本API、本地和云执行以及灵活的配置。
因为 K6是Go编写的,相对于JAVA 编写的 JMeter 有性能上的差距,K6 可以只用较少的资源就能达到指定数量的负载。
开源地址:https://github.com/grafana/k6
sudo gpg --no-default-keyring --keyring /usr/share/keyrings/k6-archive-keyring.gpg --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys C5AD17C747E3415A3642D57D77C6C491D6AC1D69
echo "deb [signed-by=/usr/share/keyrings/k6-archive-keyring.gpg] https://dl.k6.io/deb stable main" | sudo tee /etc/apt/sources.list.d/k6.list
sudo apt-get update
sudo apt-get install k6
sudo dnf install https://dl.k6.io/rpm/repo.rpm
sudo dnf install k6
brew install k6
choco install k6
winget install k6
docker pull grafana/k6
新建一个 test.js 文件
Get 请求 get( url, [params] )
import http from 'k6/http';
export let options = {
vus: 100, // 指定要同时运行的虚拟用户数量
duration: '10s', // 指定测试运行的总持续时间
};
// default 默认函数
export default function () {
// 标头
let params = { headers: { 'Content-Type': 'application/json' } };
var res=http.get("https://test.k6.io",params)
}
Post 请求 Post( url, [body],[params])
import http from 'k6/http';
export let options = {
vus: 100,
duration: '10s',
};
// default 默认函数
export default function () {
// json 字符串
let json = { content: 'linhui', image: 'images' };
// 标头
let params = { headers: { 'Content-Type': 'application/json' } };
var res = http.post("https://host/api/feedback", JSON.stringify(json), params)
console.log(res.status);
}
执行脚本
k6 run test.js
batch 批处理,顺序不能保证
import http from 'k6/http';
export let options = {
vus: 1,
duration: '10s',
};
export default function () {
let get = {
method: 'GET',
url: 'https://host/get',
};
let get1 = {
method: 'GET',
url: 'https://host/get',
};
let post = {
method: 'POST',
url: 'https://host/post',
body: {
hello: 'world!',
},
params: {
headers: { 'Content-Type': 'application/json' },
},
};
let res = http.batch([req1, req2, req3]);
}
名称 | 描述 |
---|---|
Counter | 计数器,对值进行累加 |
Gauge | 最小值、最大值和最后一个值。 |
Rate | 百分比 |
Trend | 最小值、最大值、平均值和百分位数的统计数据指标 |
K6 始终都会收集的指标
名称 | 类型 | 描述 |
---|---|---|
vue | Gauge | 当前活动的虚拟用户数 |
vue_max | Gauge | 虚拟用户的最大数量 |
iterations | Counter | 脚本中的函数被执行的次数 |
data_received | Counter | 接收到的数据量大小 |
data_sent | Counter | 发送的数据量大小 |
iteration_duration | Trend | 完成默认/主函数的一次完整迭代所花费的时间。 |
checks | Rate | checks 项的成功率 |
更多功能广大网友可以继续挖掘。