You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在K6中实现类似JMeter Throughput Controller的多API差异化吞吐量控制

在k6中实现不同API的差异化吞吐量控制

k6里没有像JMeter那样直接的吞吐量控制器,但可以通过几种方式实现不同API的流量分配需求,以下是最常用的方案:

1. 简单比例分配:基于随机概率的自定义逻辑

如果只是需要按固定比例分配流量(比如60%给API A,40%给API B),可以在默认函数里生成随机数,根据数值范围判断执行哪个请求。这种方式适合快速实现简单场景。

示例代码:

import http from 'k6/http';
import { randomIntBetween } from 'https://jslib.k6.io/k6-utils/1.2.0/index.js';

export default function () {
  // 生成1-100的随机数
  const rand = randomIntBetween(1, 100);
  
  if (rand <= 60) {
    // 60%的流量调用API A
    http.get('https://your-api-endpoint.com/a');
  } else {
    // 剩余40%调用API B
    http.get('https://your-api-endpoint.com/b');
  }
}

2. 精准吞吐量控制:使用场景(Scenarios)配置

这是k6中最推荐的方式,通过配置独立场景为每个API设置专属的吞吐量规则,还能单独控制VU数、持续时间等参数,灵活性极高。

比如要让API A维持每分钟60个请求,API B维持每分钟40个请求,可以用constant-arrival-rate执行器(固定请求速率):

示例代码:

import http from 'k6/http';

export const options = {
  scenarios: {
    api_a_traffic: {
      executor: 'constant-arrival-rate',
      rate: 60, // 每分钟发送60个请求
      timeUnit: '1m',
      duration: '5m', // 测试持续5分钟
      preAllocatedVUs: 10, // 预先分配的VU数
      maxVUs: 20, // 最大可扩容的VU数
      exec: 'callApiA', // 指定执行API A的函数
    },
    api_b_traffic: {
      executor: 'constant-arrival-rate',
      rate: 40, // 每分钟发送40个请求
      timeUnit: '1m',
      duration: '5m',
      preAllocatedVUs: 10,
      maxVUs: 20,
      exec: 'callApiB', // 指定执行API B的函数
    },
  },
};

// 单独定义API A的请求逻辑
export function callApiA() {
  http.get('https://your-api-endpoint.com/a');
}

// 单独定义API B的请求逻辑
export function callApiB() {
  http.get('https://your-api-endpoint.com/b');
}

如果需要基于固定VU数来控制吞吐量(而非固定请求数),可以替换成constant-vus执行器,不过这种方式的吞吐量会受接口响应时间影响,适合对并发数有要求的场景。

3. 迭代数分配:使用shared-iterations执行器

如果测试是基于总迭代次数分配流量,比如总1000次迭代中600次给API A,400次给API B,可以用shared-iterations执行器:

示例代码:

import http from 'k6/http';

export const options = {
  scenarios: {
    api_a: {
      executor: 'shared-iterations',
      vus: 10,
      iterations: 600, // API A执行600次迭代
      maxDuration: '5m',
      exec: 'callApiA',
    },
    api_b: {
      executor: 'shared-iterations',
      vus: 10,
      iterations: 400, // API B执行400次迭代
      maxDuration: '5m',
      exec: 'callApiB',
    },
  },
};

export function callApiA() {
  http.get('https://your-api-endpoint.com/a');
}

export function callApiB() {
  http.get('https://your-api-endpoint.com/b');
}

总结

  • 简单比例分配适合快速实现、要求不高的场景;
  • 场景配置是最灵活精准的方案,能独立控制每个API的吞吐量和测试参数;
  • 迭代数分配适合基于总任务量的流量拆分场景。

内容的提问来源于stack exchange,提问作者Sherin Paul

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 08:33:14