菜单
开源

Client

Client 是一个 HTTP 客户端构造函数,它会将其请求附加追踪信息。使用它可以将追踪上下文包含在 HTTP 请求中,以便追踪后端(例如 Grafana Tempo)可以整合其结果。

Client 类是标准 http 模块的直接替代品,它会将追踪上下文附加到请求头中,并为 HTTP 相关的 k6 输出数据点元数据添加 trace_id。它目前支持 W3C Trace ContextJaeger 追踪上下文传播格式。有关传播的详细信息,请参阅关于追踪上下文

Client 构造函数只接受一个 Options 对象作为其唯一参数。

示例

本示例演示了如何实例化一个追踪客户端,并使用它来为 HTTP 调用添加追踪上下文头。它还说明了如何将其与标准 http 模块一起使用来执行未插桩的 HTTP 调用。

JavaScript
import { check } from 'k6';
import tempo from 'https://jslib.k6.io/http-instrumentation-tempo/1.0.1/index.js';
import http from 'k6/http';

// Explicitly instantiating a tempo client allows to distinguish
// instrumented from non-instrumented HTTP calls, by keeping APIs separate.
// It also allows for finer-grained configuration control, by letting
// users changing the tracing configuration on the fly during their
// script's execution.
const instrumentedHTTP = new tempo.Client({
  propagator: 'w3c',
});

const testData = { name: 'Bert' };

export default () => {
  // Using the tracing client instance, HTTP calls will have
  // their trace context headers set.
  let res = instrumentedHTTP.request('GET', 'http://httpbin.org/get', null, {
    headers: {
      'X-Example-Header': 'instrumented/request',
    },
  });

  // The tracing client offers more flexibility over
  // the `instrumentHTTP` function, as it leaves the
  // imported standard http module untouched. Thus,
  // one can still perform non-instrumented HTTP calls
  // using it.
  res = http.post('http://httpbin.org/post', JSON.stringify(testData), {
    headers: { 'X-Example-Header': 'noninstrumented/post' },
  });

  res = instrumentedHTTP.del('http://httpbin.org/delete', null, {
    headers: { 'X-Example-Header': 'instrumented/delete' },
  });
};

等同于 HTTP 模块函数

Client 类公开了与标准 http 模块相同的 API,但 batch 方法除外。

下表列出了在标准 http 模块中具有等效功能的 Client 方法

方法等同于 HTTP描述
Client.del(url, [body], [params])http.del执行一个已插桩的 HTTP DELETE 请求。此方法的原型与 http.del 函数相同,可透明地替代它。
Client.get(url, [params])http.get执行一个已插桩的 HTTP GET 请求。此方法的原型与 http.get 函数相同,可透明地替代它。
Client.head(url, [params])http.head执行一个已插桩的 HTTP HEAD 请求。此方法的原型与 http.head 函数相同,可透明地替代它。
Client.options(url, [body], [params])http.options执行一个已插桩的 HTTP OPTIONS 请求。此方法的原型与 http.options 函数相同,可透明地替代它。
Client.patch(url, [body], [params])http.patch执行一个已插桩的 HTTP PATCH 请求。此方法的原型与 http.patch 函数相同,可透明地替代它。
Client.post(url, [body], [params])http.post执行一个已插桩的 HTTP POST 请求。此方法的原型与 http.post 函数相同,可透明地替代它。
Client.put(url, [body], [params])http.put执行一个已插桩的 HTTP PUT 请求。此方法的原型与 http.put 函数相同,可透明地替代它。
Client.request(method, url, [body], [params])http.request执行一个已插桩的 HTTP 请求。此方法的原型与 http.request 函数相同,可透明地替代它。
Client.asyncRequest(method, url, [body], [params])http.asyncRequest执行一个已插桩的 HTTP 异步请求。此方法的原型与 http.asyncRequest 函数相同,可透明地替代它。

配置

Client 实例支持使用以下 API 进行重新配置

方法描述
Client.configure(options)使用提供的 Options 重新配置追踪客户端实例