java模拟并发请求工具类(测试专用)

时间:2024-03-08 08:06:14

1.背景

  实际生产中,我们开发好接口后可能会简单的压力测试一下,也就是说模拟并发测试,测试工具类如下:

2.工具类

package tentative.normal.other;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import com.alibaba.fastjson.JSON;

import java.util.Map;
import java.util.concurrent.CountDownLatch;

/**
 * @Copyright (C) 四川XXXXXX有限公司
 * @Author: LI DONG PING
 * @Date: 2020-09-24 10:21
 * @Description: <p>
 * 并发请求工具类
 * </p>
 */
public class HttpConcurrentUtil {

    //默认并发数
    private static int num = 10;

    private static CountDownLatch cdl = new CountDownLatch(num);

    /**
     * 执行并发请求
     *
     * @param url      请求url
     * @param paramMap 请求参数
     * @param n        并发数
     */
    public static void doPost(String url, Map<String, Object> paramMap, Integer n) {
        if (n != null) {
            num = n;
        }
        for (int i = 0; i < num; i++) {
            new Thread(new HttpConcurrentUtil.UserRequest(url, paramMap)).start();
            cdl.countDown();
        }
    }

    public static class UserRequest implements Runnable {
        private String url;
        private Map<String, Object> paramMap;

        public UserRequest(String url, Map<String, Object> paramMap) {
            this.url = url;
            this.paramMap = paramMap;
        }

        @Override
        public void run() {
            try {
                cdl.await();
            } catch (Exception e) {
                e.printStackTrace();
            }
            //使用工具类发送http请求
            doPost(url, paramMap);

        }

        /**
         * 这里可以根据自己的实际情况修改具体请求方式
         *
         * @param url
         * @param paramMap
         */
        public void doPost(String url, Map<String, Object> paramMap) {
            System.out.println("当前线程名称:" + Thread.currentThread().getName());
            System.out.println("请求地址:" + url);
            HttpRequest request = HttpUtil.createRequest(Method.POST, url);

            String jsonString = JSON.toJSONString(paramMap);
            //json参数格式
            request.body(jsonString);
            //表单请求
            //request.form(paramMap);

            System.out.println("请求参数:" + jsonString);
            request.setConnectionTimeout(60 * 1000);
            String response = request.execute().body();
            System.out.println("响应结果:" + response);
        }
    }

}

 

完美!