【问题标题】:Retry http requests in k6在 k6 中重试 http 请求
【发布时间】:2019-08-04 06:27:35
【问题描述】:

我有一个基于 python requests 的 API 测试套件,可以自动重试每个请求,响应为 408 或 5xx。我正在考虑在 k6 中重新实现其中的一些以进行负载测试。 k6 是否支持重试 http 请求?

【问题讨论】:

    标签: request k6


    【解决方案1】:

    k6 中没有这样的功能,但是您可以通过包装 k6/http 函数来相当简单地添加它,例如:

    function httpGet(url, params) {
        var res; 
        for (var retries = 3; retries > 0; retries--) {
            res = http.get(url, params)
            if (res.status != 408 && res.status < 500) {
                return res;
            }
        }
        return res;
    
    }
    

    然后只需使用httpGet 而不是http.get ;)

    【讨论】:

      【解决方案2】:

      您可以创建一个可重用的重试函数并将其放入一个模块中,以便由您的测试脚本导入。

      函数可以是通用的:

      • 期望函数重试
      • 期望一个谓词来区分调用成功和失败
      • 重试上限
      function retry(limit, fn, pred) {
        while (limit--) {
          let result = fn();
          if (pred(result)) return result;
        }
        return undefined;
      }
      

      然后在调用时提供正确的参数:

      retry(
        3,
        () => http.get('http://example.com'),
        r => !(r.status == 408 || r.status >= 500));
      

      当然,您可以随意将其封装在一个或多个更具体的函数中:

      function get3(url) {
        return request3(() => http.get(url));
      }
      
      function request3(req) {
        return retry(
          3,
          req,
          r => !(r.status == 408 || r.status >= 500));
      }
      
      let getResponse = get3('http://example.com');
      let postResponse = request3(() => http.post(
        'https://httpbin.org/post',
        'body',
        { headers: { 'content-type': 'text/plain' } });
      

      奖励:您可以通过实现一个巧妙命名的函数来使调用代码更具表现力,该函数会反转其结果,而不是使用否定运算符:

      function when(pred) {
        return x => !pred(x);
      }
      

      然后

      retry(
        3,
        () => http.get('http://example.com'),
        when(r => r.status == 408 || r.status >= 500));
      

      或完全改变谓词的行为并测试失败的请求而不是成功的请求:

      function retry(fn, pred, limit) {
        while (limit--) {
          let result = fn();
          if (!pred(result)) return result;
        }
        return undefined;
      }
      
      function unless(pred) {
        return x => !pred(x);
      }
      
      retry(
        3,
        () => http.get('http://example.com'),
        r => r.status == 408 || r.status >= 500);
      retry(
        3,
        () => http.get('http://example.com'),
        unless(r => r.status != 408 && r.status < 500));
      

      【讨论】:

        猜你喜欢
        • 2015-11-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-07-14
        • 2021-10-08
        • 1970-01-01
        相关资源
        最近更新 更多