java多线程压力测试接口
1.定义一个controller,里面写个测试方法,用于postman测试
1 @GetMapping("/toTestThread") 2 public void demosendThread() { 3 4 try { 5 startTime = System.currentTimeMillis(); 6 System.out.println("CountDownLatch started at: " + startTime); 7 // 初始化计数器为1 8 CountDownLatch countDownLatch = new CountDownLatch(1); 9 for (int i = 0; i < THREAD_NUM; i++) { 10 new Thread(new Run(countDownLatch)).start(); 11 } 12 // 启动多个线程 13 countDownLatch.countDown(); 14 } catch (Exception e) { 15 System.out.println("Exception: " + e); 16 } 17 18 }
2.书写多线程
/** * 线程类 */ private class Run implements Runnable { private final CountDownLatch startLatch; public Run(CountDownLatch startLatch) { this.startLatch = startLatch; } @Override public void run() { try { // 线程等待 startLatch.await(); // 执行操作 /** 这里调用你要测试的接口 */ String msg = "{\n" + " \"name\":\"终端1\",\n" + " \"id\":\"202303110001xl\",\n" + " \"terminal\":\"COL\",\n" + " \"mtype\":\"MSGE\",\n" + " \"t\":\"2023-05-05 09:28:47.475\",\n" + " \"params\":[\n" + " {\n" + " \"kks\":\"发变811层/机组1.电压1\",\n" + " \"ref\":\"发变811层/机组1.电压1\",\n" + " \"val\":\"0.56-kV\",\n" + " \"vtype\":\"电压\",\n" + " \"t\":\"2023-05-05 09:28:47.872\"\n" + " }\n" + " ]\n" + "}"; JSONObject jsonObject = JSONObject.parseObject(msg); HelloSpringMsg helloReq = new HelloSpringMsg(); helloReq.setJson(String.valueOf(jsonObject)); //具体接口 demoSpringAction.here(helloReq); long endTime = System.currentTimeMillis(); System.out.println(Thread.currentThread().getName() + " ended at: " + endTime + ", cost: " + (endTime - startTime) + " ms."); } catch (Exception e) { e.printStackTrace(); } } }
3.两个静态变量定义
/** * 定义并发线程数量 */ public static final int THREAD_NUM = 100; /** * 开始时间 */ private static long startTime = 0L;
4.查看控制台调用情况