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*/@Slf4jclass OrderControllerTest {/*** 简单测试*/@Testvoid 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);}/*** 模拟多个请求*/@Testvoid 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);}}/*** 模拟多线程请求*/@Testvoid 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);}/*** 模拟多线程并发请求*/@Testvoid 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);}}
