Client.connect(address [,params])
打开与 gRPC 服务器的连接;将阻塞直到连接建立或抛出连接错误。不能在 init
阶段调用。
参阅 Client.close() 关闭连接。
参数 | 类型 | 描述 |
---|---|---|
address | string | gRPC 服务器的地址。应采用 host:port 形式,不带协议前缀,例如 grpc.k6.io:443 。host 必须是字面 IP 地址,或可解析为 IP 地址的主机名。port 必须是字面端口号或服务名,例如 :443 或 :https 。如果 host 是字面 IPv6 地址,则必须用方括号括起来,例如 [2001:db8::1]:80 或 [fe80::1%zone]:80 。 |
params (可选) | object | 包含附加连接参数的 ConnectParams 对象。 |
ConnectParams
名称 | 类型 | 描述 |
---|---|---|
ConnectParams.plaintext | bool | 如果为 true ,将使用明文连接到 gRPC 服务器,即不安全。默认为 false ,即通过 TLS 安全连接。 |
ConnectParams.reflect | boolean | 连接时是否使用 gRPC 服务器反射协议。 |
ConnectParams.reflectMetadata | object | 一个对象,包含用户希望添加到反射请求中的自定义元数据键值对。 |
ConnectParams.timeout | string / number | 要使用的连接超时。默认超时为 "60s" 。类型也可以是数字,在这种情况下 k6 会将其解释为毫秒,例如 60000 等效于 "60s" 。 |
ConnectParams.maxReceiveSize | number | 设置客户端可接收的最大消息大小(字节)。默认为 grpc-go 默认值,即 4MB。 |
ConnectParams.maxSendSize | number | 设置客户端可发送的最大消息大小(字节)。默认为 grpc-go 默认值,约为 2GB。 |
ConnectParams.tls (可选) | object | 连接的 TLS 设置。默认为 null 。 |
TLS
连接的 TLS 设置。如果未定义,将使用选项中的主要 TLS 配置。
名称 | 类型 | 描述 |
---|---|---|
tls.cert | string | PEM 格式的客户端证书。 |
tls.key | string | PEM 格式的客户端私钥。 |
tls.password | string | 用于解密客户端私钥的密码。 |
tls.cacerts | string / array | PEM 格式的证书颁发机构字符串。 |
示例
import grpc from 'k6/net/grpc';
const client = new grpc.Client();
export default () => {
client.connect('localhost:8080');
};
import grpc from 'k6/net/grpc';
const client = new grpc.Client();
export default () => {
client.connect('localhost:8080', { plaintext: true });
};
import grpc from 'k6/net/grpc';
import { check } from 'k6';
import { SharedArray } from 'k6/data';
import exec from 'k6/execution';
// note: the services in this example don't exist. If you would like
// to run this example, make sure to replace the URLs, and
// the cacerts, cert, key, and password variables.
const grpcArgs = new SharedArray('grpc', () => {
// Using SharedArray here so that not every VU gets a copy of every certificate a key
return [
{
host: 'foo1.grpc-quickpizza.grafana.com:443',
plaintext: false,
params: {
tls: {
cacerts: [open('cacerts0.pem')],
cert: open('cert0.pem'),
key: open('key0.pem'),
},
},
},
{
host: 'foo2.grpc-quickpizza.grafana.com:443',
params: {
plaintext: false,
tls: {
cacerts: open('cacerts1.pem'),
cert: open('cert1.pem'),
key: open('key1.pem'),
password: 'cert1-passphrase',
},
},
},
];
});
const client = new grpc.Client(null, 'quickpizza.proto');
export default () => {
if (__ITER === 0) {
// Take one config and use it for this one VU
const grpcArg = grpcArgs[exec.vu.idInTest % grpcArgs.length];
client.connect(grpcArg.host, grpcArg.params);
}
const response = client.invoke('quickpizza.GRPC/Status');
check(response, {
'status is OK': (r) => r && r.status === grpc.StatusOK,
});
console.log(JSON.stringify(response.message));
};