详解Grafana k6 的阈值(Thresholds)

发布于:2025-09-03 ⋅ 阅读:(13) ⋅ 点赞:(0)

k6 的阈值(Thresholds)是定义性能测试通过/失败标准的核心机制,允许您为关键指标设置可接受的性能边界。当测试结果超过阈值时,k6 会返回非零退出码,标记测试失败。

一、阈值核心概念

  1. 定义位置:在 options 对象中声明

    export const options = {
      thresholds: {
        // 阈值规则在此定义
      }
    };
  2. 基本语法

    '指标名{标签过滤}': [ '条件1', '条件2' ]
  3. 执行特点

    • 实时评估(测试期间持续监控)

    • 测试结束时进行最终评估

    • 任意阈值失败 → 整个测试失败(exit code ≠ 0)

二、常用阈值参数详解

1. HTTP 请求相关指标
参数 含义 用法示例 说明
http_req_duration 请求总耗时(ms) 'p(95)<500' 95%请求耗时<500ms
http_req_failed 请求失败率 'rate<0.01' 失败率<1%
http_req_waiting 等待服务器响应时间(TTFB) 'max<1000' 最大等待时间<1s
http_req_connecting TCP连接时间 'avg<50' 平均连接时间<50ms

标签过滤示例

thresholds: {
  'http_req_duration{status:200}': ['p(95)<300'], // 仅监控200响应
  'http_req_duration{method:POST}': ['p(90)<800'] // 仅监控POST请求
}
2. 测试流程指标
参数 含义 用法示例 说明
iterations 完成的迭代总数 'count>1000' 至少完成1000次迭代
iteration_duration 单次迭代耗时 'p(99)<5000' 99%迭代耗时<5s
vus 虚拟用户数 'value>50' 峰值VU数>50
vus_max 配置的最大VU数 'value==100' 验证VU配置正确性
3. 自定义检查指标
import { check } from 'k6';

// 定义检查点
export default function () {
  check(res, {
    '状态码是200': (r) => r.status === 200,
    '包含有效数据': (r) => r.json().data.length > 0
  });
}

// 阈值配置
thresholds: {
  'checks{name:包含有效数据}': ['rate>0.99'] // 特定检查成功率>99%
}
4. 自定义指标阈值
import { Trend, Rate } from 'k6/metrics';

// 创建自定义指标
const authDuration = new Trend('auth_duration');
const premiumRate = new Rate('premium_users');

// 阈值配置
thresholds: {
  'auth_duration': ['p(90)<200'], 
  'premium_users': ['rate>0.2']   // 20%用户是高级用户
}

三、阈值运算符详解

1. 时间类型指标(Trend)
运算符 示例 含义
avg 'avg<500' 平均值<500ms
min 'min>100' 最小值>100ms
max 'max<2000' 最大值<2000ms
p(percent) 'p(99)<800' 99百分位数<800ms
med 'med<400' 中位数<400ms
2. 比率类型指标(Rate)
运算符 示例 含义
rate 'rate>0.95' 成功率>95%
count 'count>100' 发生次数>100

四、高级用法示例

1. 多条件组合
thresholds: {
  http_req_duration: [
    'max<3000',     // 硬性要求:所有请求<3s
    'p(99)<1500',   // 关键要求:99%请求<1.5s
    'p(95)<800'     // 优化要求:95%请求<800ms
  ]
}
2. 分阶段阈值(结合Scenarios)
scenarios: {
  spike_test: {
    executor: 'ramping-vus',
    stages: [
      { duration: '1m', target: 100 },
      { duration: '3m', target: 500 }
    ],
    thresholds: {
      'http_req_duration{stage:spike}': ['p(95)<1000'] // 仅针对此场景
    }
  }
}
3. 错误熔断机制
thresholds: {
  http_req_failed: [
    { threshold: 'rate<0.02', abortOnFail: true } // 错误率>2%时立即终止测试
  ]
}

五、最佳实践建议

  1. 关键指标优先

    // 核心三件套
    'http_req_failed': ['rate<0.01'],    // 错误率<1%
    'http_req_duration': ['p(95)<500'],  // 95%请求<500ms
    'checks': ['rate>0.99']              // 检查点>99%通过率
  2. 分层设置阈值

    • 严格阈值:核心业务流(如登录/支付)

    • 宽松阈值:非关键路径(如静态资源)

  3. 结合标签精细化监控

    'http_req_duration{group:::重要API}': ['p(90)<300'],
    'http_req_duration{group:::次要API}': ['p(90)<800']
  4. 在CI/CD中的典型应用

    k6 run --threshold-http-req-failed="rate<0.01" script.js


网站公告

今日签到

点亮在社区的每一天
去签到