线程配置类
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;
}
};
}
}