写点什么

压测脚本

用户头像
LEAF
关注
发布于: 2020 年 07 月 20 日

背景:练习编写压测脚本

目标:使用熟悉的语言写一个性能压测脚本,输出平均响应时间和95%响应时间。

思路:使用OkHttp包完成网络请求,使用java8的Lambda表达式编写并发请求。

/*
* This Java source file was generated by the Gradle 'init' task.
*/
package week06;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import java.io.IOException;
public class App {
public Long httpGet(String url) {
OkHttpClient client = new OkHttpClient().newBuilder()
//.addNetworkInterceptor(new NetworkInterceptorRecord())
.build();
Request request = new Request.Builder()
.url(url)
.build();
try (Response response = client.newCall(request).execute()) {
return response.receivedResponseAtMillis() - response.sentRequestAtMillis();
} catch(IOException ex) {
return 0L;
}
}
}



/*
* This Java source file was generated by the Gradle 'init' task.
*/
package week06;
import org.junit.Test;
import static org.junit.Assert.*;
import java.util.List;
import java.util.ArrayList;
import java.util.stream.Collectors;
import java.util.concurrent.CompletableFuture;
import java.io.IOException;
public class AppTest {
@Test public void testAppHasAGreeting() throws IOException{
int times = 10;
//
String url = "https://www.baidu.com";
List<App> apps = new ArrayList<>();
for (int i = 0; i < times; i++) {
apps.add(new App());
}
//
for (int i = 0; i < times; i++) {
long startReq = System.currentTimeMillis();
List<Long> cost = apps.parallelStream()
.map(app -> app.httpGet(url))
.collect(Collectors.toList());
long endReq = System.currentTimeMillis();
System.out.println("共耗时:"+(endReq - startReq));
}
//
//System.out.println("共耗时:"+(endReq - startReq));
//assertEquals("app should have a greeting", times, cost.size());
}
}



用户头像

LEAF

关注

还未添加个人签名 2018.10.08 加入

还未添加个人简介

评论 (1 条评论)

发布
用户头像
请添加“极客大学架构师训练营”标签,方便分类
2020 年 07 月 21 日 10:56
回复
没有更多了
压测脚本