Java实现压测程序

线程配置类


import lombok.Data;

import java.io.Serializable;

/**
 * @author 
 * @date 
 */
@Data
public class ConnectionConfig implements Serializable {
    private static final long serialVersionUID = 8755556417537605401L;

    /**
     * 线程数
     */
    private int threadCount;

    /**
     * 运行时间(秒)
     */
    private long runTimeSec;

    /**
     * 统计的时间间隔(秒)
     */
    private Integer delaySec;
}

实际压测程序


import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Optional;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.LongAdder;
import java.util.function.Predicate;
import java.util.function.Supplier;

/**
 * 压测工具类
 *
 * @author 
 * @date 
 */
public class PressureTestUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(PressureTestUtil.class);

    /**
     * 封装中间重复代码
     *
     * @param config    压测配置
     * @param supplier  需要实际执行的代码,内容为被压测的代码,支持返回结果
     * @param predicate 结果判断函数,结果为false,则失败数+1
     * @return
     * @throws InterruptedException
     */
    public static  <T> JSONObject invoke(ConnectionConfig config, Supplier<T> supplier, Predicate<T> predicate) throws InterruptedException {

        // 线程数
        int threadCount = config.getThreadCount();
        // 执行时间
        long runTime = config.getRunTimeSec();
        // 统计间隔
        Integer delaySec = Optional.ofNullable(config.getDelaySec()).orElse(5);

        //记录总数和失败数(允许数量有差异,因此使用LongAdder提高计算能力)
        LongAdder sumAdder = new LongAdder();
        LongAdder failAdder = new LongAdder();

        //记录开始时间
        long startTime = System.currentTimeMillis();

        //新建一个定时任务线程池,用于每隔5秒打印一次时间,当前请求数,当前错误数,qps
        ScheduledThreadPoolExecutor scheduled = new ScheduledThreadPoolExecutor(1, initFactory("monitor-pool-"));
        scheduled.scheduleAtFixedRate(() -> {
                    long sumCount = sumAdder.longValue();
                    long useSeconds = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis() - startTime);
                    double qps = BigDecimal.valueOf(sumCount).divide(BigDecimal.valueOf(useSeconds), 5, RoundingMode.HALF_UP).doubleValue();
                    LOGGER.info("已运行{}秒, 请求总数:{}, 失败数量:{}, QPS:{}", useSeconds, sumCount, failAdder.longValue(), qps);
                },
                delaySec, delaySec, TimeUnit.SECONDS
        );

        //构建用于压测的线程池
        ExecutorService threadPool = new ThreadPoolExecutor(threadCount, threadCount, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(), initFactory("task-pool-"));
        CountDownLatch downLatch = new CountDownLatch(threadCount);
        while (downLatch.getCount() > 0) {
            // 线程池空转,用于预热
            threadPool.submit(downLatch::countDown);
        }
        downLatch.await();
        LOGGER.info("=============== 所有线程预热完成,压测开始 ===============");

        long runMillis = TimeUnit.SECONDS.toMillis(runTime);

        // 开启线程
        CountDownLatch count = new CountDownLatch(threadCount);
        for (int i = 0; i < threadCount; i++) {

            // 提交任务
            threadPool.submit(() -> {

                // 每个任务都循环请求不同接口
                while (System.currentTimeMillis() - startTime <= runMillis) {
                    try {

                        // 执行测试代码,并判断结果
                        if (!predicate.test(supplier.get())) {
                            failAdder.increment();
                        }
                    } finally {
                        sumAdder.increment();
                    }
                }

                // 每次任务结束计数器减一
                count.countDown();
            });
        }
        count.await();
        LOGGER.info("=============== 压测结束 ===============");

        //停止线程池
        scheduled.shutdown();
        threadPool.shutdown();

        // 返回压测结果
        JSONObject object = new JSONObject(true);
        long sumCount = sumAdder.longValue();
        long failCount = failAdder.longValue();
        object.put("执行总数:", sumCount);
        object.put("成功数:", sumCount - failCount);
        object.put("失败数:", failCount);
        BigDecimal sumDecimal = BigDecimal.valueOf(sumCount);
        BigDecimal failDecimal = BigDecimal.valueOf(failCount);
        object.put("错误率:", failDecimal.divide(sumDecimal, 5, RoundingMode.HALF_UP).doubleValue() * 100 + "%");

        // 耗时
        long useSeconds = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis() - startTime);
        BigDecimal useSecondsDecimal = BigDecimal.valueOf(useSeconds);
        object.put("QPS:", sumDecimal.divide(useSecondsDecimal, 5, RoundingMode.HALF_UP));

        LOGGER.info("运行总时间:{}秒", useSeconds);
        object.forEach((k, v) -> LOGGER.info("{}:{}", k, v));
        return object;
    }

    private static ThreadFactory initFactory(String prefix) {
        return new ThreadFactory() {
            AtomicInteger count = new AtomicInteger(1);

            @Override
            public Thread newThread(Runnable r) {
                Thread thread = new Thread(r, prefix + count.getAndIncrement());
                LOGGER.debug("create thread:[{}]", thread.getName());
                return thread;
            }
        };
    }
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值