3. 有了发送请求的客户端,那如何能够更简单的实现一个协议好让客户端发送,再贴一段代码^_^:
1 package tea.client.network;
2
3 import org.apache.jmeter.config.Arguments;
4 import org.apache.jmeter.protocol.java.sampler.AbstractJavaSamplerClient;
5 import org.apache.jmeter.protocol.java.sampler.JavaSamplerContext;
6 import org.apache.jmeter.samplers.SampleResult;
7 import com.google.protobuf.InvalidProtocolBufferException;
8 import com.google.protobuf.MessageLite;
9
10 /**
11 * @author Teaey
12 * @creation 2012-8-25
13 */
14 public abstract class BaseSample extends AbstractJavaSamplerClient
15 {
16 public static final String PARAM_IP = "ip";
17 public static final String PARAM_PORT = "port";
18 public static final String VAR_IP = "${ip}";
19 public static final String VAR_PORT = "${port}";
20 protected BaseClient client;
21 public void addParameter(Arguments params)
22 {
23 }
24 /**
25 * Jmeter获取消息参数,默认配置ip和port两个参数
26 * 如果子类有更多参数,调用super.getDefaultParameters()获取Arguments后,继续设置其他方法
27 */
28 @Override
29 public Arguments getDefaultParameters()
30 {
31 System.out.println("1.getDefaultParameters");
32 Arguments params = new Arguments();
33 params.addArgument(PARAM_IP, VAR_IP);
34 params.addArgument(PARAM_PORT, VAR_PORT);
35 addParameter(params);
36 return params;
37 }
38 /**
39 * runTest的前置方法
40 */
41 @Override
42 public void setupTest(JavaSamplerContext context)
43 {
44 System.out.println("2.setupTest:" + context.containsParameter(PARAM_IP));
45 String ip = context.getParameter(PARAM_IP);
46 String port = context.getParameter(PARAM_PORT);
47 this.client = NetworkClientHolder.getClient(ip, port);
48 System.out.println("thread--->" + Thread.currentThread().getId() + " client--->" + client);
49 }
50 /**
51 * Jmeter调用,用于实际的测试
52 */
53 @Override
54 public SampleResult runTest(JavaSamplerContext context)
55 {
56 SampleResult sample = getSample();
57 sample.sampleStart();
58 try
59 {
60 MessageLite response = doTest();
61 String msg = response == null ? "" : response.toString();
62 sample.setResponseMessage(msg);
63 sample.setSuccessful(true);
64 } catch (Exception e)
65 {
66 sample.setSuccessful(false);
67 e.printStackTrace();
68 } finally
69 {
70 sample.sampleEnd();
71 }
72 return sample;
73 }
74 /**
75 * 获取本Sample的标签,子类实现
76 */
77 public abstract String getLabel();
78 /**
79 * 获取一个带标签的Sample
80 */
81 public SampleResult getSample()
82 {
83 SampleResult sample = new SampleResult();
84 sample.setSampleLabel(getLabel());
85 return sample;
86 }
87 /**
88 * Jmeter调用,用于
89 */
90 @Override
91 public void teardownTest(JavaSamplerContext context)
92 {
93 System.out.println("4.teardownTest");
94 }
95 /**
96 * 需实现,具体测试的方法,调用client的send/sendWithBack发送请求
97 * 如无返回,放回null即可
98 */
99 public abstract MessageLite doTest() throws InvalidProtocolBufferException;
100 }
好的,这里封装了下AbstractJavaSamplerClient,每个消息默认包含ip和port参数,这可以再jmeter的用户变量中定义好。为了方便大家添加消息的参数,这里实现了空的