Client
注意
实验模块k6/experimental/tracing
已弃用,其功能已完全作为jslib提供。请参考其文档。k6/experimental/tracing
将在未来移除。
Client
是一个HTTP客户端构造函数,它将跟踪信息附加到其请求中。使用它在HTTP请求中包含跟踪上下文,以便跟踪后端(例如Grafana Tempo)可以合并其结果。
Client
类充当标准http
模块的直接替换,并附加一个跟踪上下文到请求标头,并在HTTP相关k6输出的数据点元数据中添加一个trace_id
。它目前支持W3C跟踪上下文和Jaeger跟踪上下文传播格式。有关传播的详细信息,请参考关于跟踪上下文。
Client
构造函数接受一个Options
对象作为其唯一参数。
示例
此示例演示如何实例化一个跟踪客户端并使用它为HTTP调用添加跟踪上下文标头。它还说明了如何与标准http
模块一起使用它来执行非跟踪的HTTP调用。
import { check } from 'k6';
import tracing from 'k6/experimental/tracing';
import http from 'k6/http';
// Explicitly instantiating a tracing client allows to distringuish
// 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 tracing.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
方法,它不存在于Client
中。下表列出了Client
方法,它们在标准http
模块中有等效项
方法 | 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 HEAD请求。该方法与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 重新配置跟踪客户端实例 |