JUC高併發程式設計(三)之模擬介面壓力測試
阿新 • • 發佈:2022-01-02
1.背景
介面壓力測試是產品上線前很重要的一項測試,我們可以使用很多開源工具測試,
當然我們也可以簡單的寫一個多執行緒併發測試案例
2.程式碼
controller介面
/** * 查詢訂單 * * @return */ @RequestMapping("/api/order") public Object product(Integer id) { // 為了便於分析,設定一個執行緒號 Thread.currentThread().setName("thread-" + id); log.info("查詢訂單-" + id); // 模擬隨機耗時 ThreadUtil.sleepRandom(); return "訂單編號-" + id; }
3.測試
測試程式碼
package com.ldp.jucproject.controller; import cn.hutool.http.HttpRequest; import cn.hutool.http.HttpUtil; import com.ldp.jucproject.utils.ThreadUtil; import lombok.extern.slf4j.Slf4j;import org.junit.jupiter.api.Test; import java.util.concurrent.CountDownLatch; /** * @author 姿勢帝-部落格園 * @address https://www.cnblogs.com/newAndHui/ * @WeChat 851298348 * @create 11/06 10:18 * @description */ @Slf4j class OrderControllerTest { /** * 簡單測試 */ @Test void product01() { Integer id= 1; String url = "http://localhost:8001/api/order?id=" + id; HttpRequest request = HttpUtil.createGet(url); String response = request.execute().body(); System.out.println("response=" + response); } /** * 模擬多個請求 */ @Test void product02() { for (int i = 1; i <= 100; i++) { Integer id = i; String url = "http://localhost:8001/api/order?id=" + id; HttpRequest request = HttpUtil.createGet(url); String response = request.execute().body(); System.out.println("response=" + response); } } /** * 模擬多執行緒請求 */ @Test void product03() throws InterruptedException { for (int i = 1; i <= 100; i++) { ThreadUtil.sleepRandom(); Integer id = i; new Thread(() -> { String url = "http://localhost:8001/api/order?id=" + id; System.out.println("待查詢訂單號=" + id); HttpRequest request = HttpUtil.createGet(url); String response = request.execute().body(); System.out.println("response=" + response); }).start(); } // 避免執行緒終止 Thread.sleep(20 * 1000); } /** * 模擬多執行緒併發請求 */ @Test void product04() throws Exception { // 併發請求數 int num = 100; CountDownLatch countDownLatch = new CountDownLatch(num); for (int i = 1; i <= num; i++) { ThreadUtil.sleepRandom(); // 計數器減一 countDownLatch.countDown(); Integer id = i; new Thread(() -> { try { String url = "http://localhost:8001/api/order?id=" + id; // 等待計數器歸零,歸零前都是處於阻塞狀態 System.out.println("待查詢訂單號=" + id); countDownLatch.await(); HttpRequest request = HttpUtil.createGet(url); String response = request.execute().body(); System.out.println("response=" + response); } catch (Exception e) { log.error("模擬併發出錯:{}", e); } }).start(); } // 避免執行緒終止 Thread.sleep(60 * 1000); } }