4. k6 核心 API:http.get/post/put/delete、check、group、sleep、metrics 自定义

本章是 k6 脚本开发的基石。你将掌握 HTTP 请求方法、结果校验、逻辑分组、思考时间模拟以及自定义指标上报。这些 API 构成了压测脚本的“动词”与“量尺”,是后续编排复杂巡检场景的必备技能。

4.1 HTTP 请求方法:get / post / put / delete

k6 的 http 模块提供了与 RESTful API 一一对应的请求方法。所有方法均返回一个 Response 对象,包含状态码、响应体、响应头、耗时等属性。

方法 语法 典型场景
GET http.get(url, [params]) 查询资源、健康检查、页面加载
POST http.post(url, body, [params]) 创建资源、提交表单、登录认证
PUT http.put(url, body, [params]) 全量更新资源、替换配置
DELETE http.del(url, [params]) 删除资源、清理测试数据
参数对象 params 常用字段:
headers:自定义请求头(如 Authorization、Content-Type)
tags:为请求打标签,用于后续指标过滤与聚合
timeout:超时时间(毫秒),默认 60s
auth:便捷的 HTTP 基本认证
import http from 'k6/http';

export default function () {
  // GET 请求
  let getRes = http.get('https://api.example.com/users/1', {
    headers: { 'Accept': 'application/json' },
    tags: { name: 'getUser' }
  });

  // POST 请求
  let payload = JSON.stringify({ name: '张三', role: 'admin' });
  let postRes = http.post('https://api.example.com/users', payload, {
    headers: { 'Content-Type': 'application/json' }
  });

  // PUT 请求
  let updatePayload = JSON.stringify({ name: '张三', role: 'superadmin' });
  let putRes = http.put('https://api.example.com/users/1', updatePayload, {
    headers: { 'Content-Type': 'application/json' }
  });

  // DELETE 请求
  let delRes = http.del('https://api.example.com/users/1');
}

4.2 check:断言式结果校验

check 是 k6 内置的断言函数,用于验证 HTTP 响应是否符合预期。它接受一个响应对象和一个包含多个断言键值对的对象。每个断言返回布尔值,k6 自动统计通过/失败次数并上报为 checks 指标。

import { check } from 'k6';
import http from 'k6/http';

export default function () {
  let res = http.get('https://api.example.com/health');

  check(res, {
    '状态码为 200': (r) => r.status === 200,
    '响应时间 < 500ms': (r) => r.timings.duration < 500,
    '响应体包含 "ok"': (r) => r.body.includes('ok'),
    '响应头 Content-Type 为 JSON': (r) => r.headers['Content-Type'] === 'application/json',
  });
}
注意:check 失败不会终止脚本执行,也不会抛出异常。它仅用于统计和告警。若需要失败时停止 VU,应结合 thresholds 或手动 throw 处理。

4.3 group:逻辑分组与指标聚合

group 用于将一组请求或操作包裹为一个逻辑单元。k6 会为每个 group 单独计算请求速率、耗时分布、失败率等指标,在 HTML 报告中以折叠面板展示,极大提升可读性。

import { group } from 'k6';
import http from 'k6/http';

export default function () {
  group('用户登录流程', function () {
    let loginRes = http.post('https://api.example.com/login', {
      username: 'testuser',
      password: 'testpass'
    });
    check(loginRes, { '登录成功': (r) => r.status === 200 });
  });

  group('获取用户信息', function () {
    let profileRes = http.get('https://api.example.com/profile', {
      headers: { 'Authorization': 'Bearer token123' }
    });
    check(profileRes, { '获取资料成功': (r) => r.status === 200 });
  });
}
最佳实践:按业务事务(Transaction)划分 group,如“下单流程”、“支付回调”、“数据同步”。每个 group 内包含 2~5 个请求,避免单个 group 过大导致指标粒度丢失。

4.4 sleep:模拟用户思考时间

sleep 函数让当前 VU 暂停执行指定秒数,用于模拟真实用户在操作间的停顿。它直接影响请求速率(RPS),是控制压测负载形态的关键工具。

import { sleep } from 'k6';

export default function () {
  http.get('https://api.example.com/page1');
  sleep(1);   // 模拟用户阅读页面 1 秒

  http.get('https://api.example.com/page2');
  sleep(2.5); // 模拟用户填写表单 2.5 秒

  http.post('https://api.example.com/submit', { data: 'test' });
  sleep(0.5); // 模拟提交后等待响应
}
场景 推荐 sleep 范围 说明
轻量 API 巡检 0.1s ~ 0.5s 快速轮询,高 RPS
Web 页面浏览 1s ~ 5s 模拟用户阅读与操作
复杂业务流程 2s ~ 10s 包含多步骤表单、确认弹窗
容量摸底测试 0s ~ 1s 消除思考时间,压测系统极限

4.5 自定义 metrics:精准度量业务指标

k6 允许你定义四种自定义指标类型,用于度量业务层面的性能数据,如“订单创建耗时”、“支付成功率”、“缓存命中率”。

指标类型 构造函数 适用场景
Counter new Counter('name') 计数类,如失败次数、重试次数
Gauge new Gauge('name') 瞬时值,如当前连接数、队列深度
Trend new Trend('name') 分布统计,如响应时间、数据包大小
Rate new Rate('name') 比率统计,如成功率、错误率
import { Counter, Trend, Rate } from 'k6/metrics';
import { check } from 'k6';
import http from 'k6/http';

// 定义自定义指标
let orderSuccessRate = new Rate('order_success_rate');
let orderDuration = new Trend('order_duration_ms');
let retryCounter = new Counter('order_retry_count');

export default function () {
  let start = Date.now();

  let res = http.post('https://api.example.com/orders', {
    productId: 'P1001',
    quantity: 2
  });

  let duration = Date.now() - start;
  orderDuration.add(duration);  // 记录订单耗时

  let success = check(res, { '订单创建成功': (r) => r.status === 201 });
  orderSuccessRate.add(success); // 记录成功率

  if (!success) {
    retryCounter.add(1); // 记录重试次数
  }
}
自定义指标在巡检脚本中的价值:
• 将业务成功/失败映射为 Rate 指标,直接设置阈值告警
• 用 Trend 记录关键接口的 P95/P99 耗时,发现性能劣化趋势
• 结合 group 标签,按业务模块聚合自定义指标,快速定位瓶颈

4.6 核心 API 协作流程

下图展示了在一次 VU 迭代中,核心 API 的典型调用顺序与数据流向。

k6 核心 API 协作流程(单次 VU 迭代) VU 迭代开始 group("登录流程") http.post("/login") check(res, { "登录成功" }) sleep(1.5) // 思考时间 自定义指标:Trend / Rate / Counter 上报 迭代结束 核心 API 职责 • http.* : 发送请求 • check : 断言校验 • group : 逻辑分组 • sleep : 思考时间

4.7 综合示例:巡检脚本片段

以下示例融合了本章所有核心 API,模拟一个电商系统的订单巡检场景。

import http from 'k6/http';
import { check, group, sleep } from 'k6';
import { Rate, Trend } from 'k6/metrics';

let orderFailRate = new Rate('order_fail_rate');
let orderLatency = new Trend('order_latency_ms');

export default function () {
  group('商品浏览', function () {
    let res = http.get('https://shop.example.com/products?page=1');
    check(res, {
      '商品列表加载成功': (r) => r.status === 200,
      '返回商品数量 > 0': (r) => JSON.parse(r.body).length > 0,
    });
    sleep(1);
  });

  group('创建订单', function () {
    let start = Date.now();
    let payload = JSON.stringify({
      productId: 'P1001',
      quantity: 1,
      userId: 'U8888'
    });
    let res = http.post('https://shop.example.com/orders', payload, {
      headers: { 'Content-Type': 'application/json' }
    });
    let duration = Date.now() - start;
    orderLatency.add(duration);

    let success = check(res, {
      '订单创建成功': (r) => r.status === 201,
      '响应包含 orderId': (r) => JSON.parse(r.body).orderId !== undefined,
    });
    orderFailRate.add(!success);
    sleep(2);
  });

  group('查询订单', function () {
    let res = http.get('https://shop.example.com/orders/U8888');
    check(res, {
      '订单查询成功': (r) => r.status === 200,
      '订单状态正确': (r) => JSON.parse(r.body).status === 'pending',
    });
    sleep(0.5);
  });
}
巡检脚本编排要点:
• 每个 group 对应一个完整的业务操作单元,便于报告分析
• check 覆盖状态码、响应体结构、业务字段,确保功能正确性
• 自定义指标记录关键业务的耗时与成功率,用于阈值告警
• sleep 模拟真实用户节奏,避免压测变成“无脑轰炸”