写点什么

并发测试 JAVA

用户头像
王麒宇
关注
发布于: 2020 年 07 月 22 日
  1. 利用线程线程池结合 CountDownLatch 调用 http 请求 实现高并发 api 性能测试

  2. 用 JAVA8 的 lamdba 表达式对接口调用时间进行求平均值

  3. JAVA 类如下:

@RunWith(SpringJUnit4ClassRunner.class)@SpringBootTest(classes = Application.class)@ActiveProfiles("dev")public class MyTest {
@Bean private RestTemplate restTemplate(){ return new RestTemplate(); } /** * 定义并发线程数量 */ private static final int THREAD_NUM = 100; private static final List<Long> httpTimeList = new ArrayList<>();
@Test public void test() { try { ExecutorService executorService = Executors.newFixedThreadPool(THREAD_NUM); // 初始化计数器为1 CountDownLatch countDownLatch = new CountDownLatch(1); for (int i = 0; i < THREAD_NUM; i ++) { executorService.execute(new Task(countDownLatch, httpTimeList)); } // 启动多个线程 countDownLatch.countDown();
executorService.shutdown(); while (!executorService.isTerminated()) { try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } } Collections.sort(httpTimeList); double average = httpTimeList.stream().mapToLong(Long::longValue).average().getAsDouble(); System.out.println("平均响应时间:" + average); System.out.println("95%响应时间:" + httpTimeList.get(94)); } catch (Exception e) { System.out.println("Exception: " + e); } }
/** * 线程类 */ private class Task implements Runnable { private final CountDownLatch startLatch; private final List<Long> httpTimeList;
public Task(CountDownLatch startLatch, List<Long> httpTimeList) { this.startLatch = startLatch; this.httpTimeList = httpTimeList; }
@Override public void run() { try { // 线程等待 startLatch.await(); long startTime = SystemClock.now(); restTemplate().getForEntity("https://www.baidu.com", String.class); long endTime = SystemClock.now(); System.out.println(Thread.currentThread().getName() + " ended at: " + endTime + ", cost: " + (endTime - startTime) + " ms."); httpTimeList.add((endTime - startTime)); } catch (Exception e) { e.printStackTrace(); } } }
}
复制代码

测试结果:

平均响应时间:620.21

95%响应时间:637

用户头像

王麒宇

关注

还未添加个人签名 2018.03.27 加入

还未添加个人简介

评论

发布
暂无评论
并发测试JAVA