带有 gRPC Java 客户端和 BeanShell 采样器的 JMeter

问题描述

为什么不能在 JMeter 的 BeanShell Sampler 之外运行这个原生 Java gRPC 客户端:

package at.fhj.swd.grpc.client;

import at.fhj.swd.grpc.CalcRequest;
import at.fhj.swd.grpc.CalcResponse;
import at.fhj.swd.grpc.CalcServiceGrpc;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;

public class Grpcclient {

public static void calc() {
    ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost",9090)
            .usePlaintext()
            .build();

    CalcServiceGrpc.CalcServiceBlockingStub stub
            = CalcServiceGrpc.newBlockingStub(channel);
    CalcResponse calcResponse = stub.calc(CalcRequest.newBuilder()
            .setNumber(7)
            .build());

    channel.shutdown();

    System.out.println(calcResponse.getResultList());
    }
}

BeanShell Sampler Script 无法创建 GrpcCient 的实例。 (引用方法调用

import at.fhj.swd.grpc.client.Grpcclient;

Grpcclient grpcclient = new Grpcclient();

//grpcclient.calc();

错误

Response code:500
Response message:org.apache.jorphan.util.JMeterException: Error invoking bsh method: eval   io/grpc/Channel

似乎导入有问题,但为什么呢?客户端在没有 JMeter 的情况下运行。

解决方法

  1. Beanshell 与 Java 并非 100% 兼容,因此如果存在重载的函数/构造函数,您需要通过 reflection
  2. 明确指定您想要的函数/构造函数
  3. Since JMeter 3.1 it's recommended to use JSR223 Test Elements and Groovy 因此只需从语言下拉列表中选择 groovy 就足够了,您的代码将开始按预期工作。此外,与 Beanshell 相比,Groovy 的性能要好得多,请参阅Apache Groovy - Why and How You Should Use It 文章了解更多详情