一,什么是jmeter java请求
二,准备工作
需要一些java基础及java开发环境(推荐IDEA)
三,实施阶段
1.编写待导入的函数
package xx.xx;
import kafka.javaapi.producer.Producer;
import kafka.producer.KeyedMessage;
import kafka.producer.ProducerConfig;
import org.apache.jmeter.config.Arguments;
import org.apache.jmeter.protocol.java.sampler.AbstractJavaSamplerClient;
import org.apache.jmeter.protocol.java.sampler.JavaSamplerContext;
import org.apache.jmeter.samplers.SampleResult;
import java.util.Properties;
//创建自己的函数类,继承AbstractJavaSamplerClient类
public class KafkaSampler extends AbstractJavaSamplerClient {
public static void main(String[] args) {
Arguments args0 = new Arguments();//参数
KafkaSampler test = new KafkaSampler();
JavaSamplerContext context = new JavaSamplerContext(args0);
test.setupTest(context);//setup,可以不用
test.runTest(context);//java请求实现
test.teardownTest(context);//teardown,可以不用
}
public SampleResult runTest(JavaSamplerContext context) {
SampleResult results = new SampleResult();
results.sampleStart(); //记录开始时间
try {//java请求实现
String brokerList = context.getParameter("BrokerList");
String topic = context.getParameter("Topic");
String content = context.getParameter("Content");
String serializer = context.getParameter("Serializer");
//设置请求信息
results.setSamplerData("kafka://" + brokerList + "/" + topic + "?" + content);
Properties props = new Properties();
props.put("serializer.class", serializer);
props.put("metadata.broker.list", brokerList);
ProducerConfig config = new ProducerConfig(props);
Producer<String, String> producer = new Producer<String, String>(config);
//Send one message.
KeyedMessage<String, String> message =
new KeyedMessage<String, String>(topic, content);
producer.send(message);
//请求成功时的结果信息
result.setResponseData("Success", "utf8");
result.setSuccessful(true);
result.setResponseCode("0");
result.setResponseMessage("OK");
} catch (Throwable e) {//异常时设置结果和响应信息
result.setResponseData(e.toString(), "utf8");
result.setSuccessful(false);
result.setResponseCode("-1");
result.setResponseMessage("Not OK");
}
results.sampleEnd(); //记录结束时间
return results;
}
public void setupTest(JavaSamplerContext context) {
}
public void teardownTest(JavaSamplerContext context) {
}
@Override
public Arguments getDefaultParameters() {//定义默认参数
Arguments args = new Arguments();
args.addArgument("BrokerList", "");
args.addArgument("Topic", "");
args.addArgument("Content", "");
args.addArgument("Serializer", "kafka.serializer.StringEncoder");
return args;
}
}
基本可以看出只需要编写runTest这个方法,其他都是套路。