简介:本文演示怎么用java模拟Jmeter的压测操作
首先需要导入hutool
包
Hutool 是一个 Java 工具包,它提供了一些常用的工具方法,旨在简化 Java 编程。Hutool 包含了多种工具类,例如:
日期时间处理:提供日期时间的解析、格式化、计算等。 字符串处理:字符串的拼接、分割、转换等。 文件操作:文件的读写、文件路径解析等。 加密解密:支持多种加密算法。 HTTP客户端:发送 HTTP 请求的工具。 JSON处理:JSON数据的解析和生成。 图像处理:生成验证码图片等。 Bean操作:Java Bean的属性操作等。 Hutool 的设计哲学是减少代码量,提高开发效率,让开发者能够更专注于业务逻辑的实现
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.11</version> <!-- 使用最新版本 -->
</dependency>
代码思路:
public class JmeterTest {
public static void main(String[] args) {
String url = "xxxxxxxxxxxxxxx"; // 待压测的接口
// 模拟底层请求
int threadCount = 20;
for (int i = 0; i < threadCount; ++ i)
{
new Thread(new Runnable() {
@Override
public void run() {
while(true){
String response = HttpUtil.get(url);
}
}
}).start();
}
}
}
线程池优化的好处
import cn.hutool.http.HttpUtil;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class JmeterTest {
public static void main(String[] args) {
String url = "xxxxxxxxxxxxxxx"; // 待压测的接口
int threadCount = 20; // 线程数
// 模拟底层请求
ExecutorService executorService = Executors.newFixedThreadPool(threadCount);
for (int i = 0; i < threadCount; ++ i){
try {
executorService.submit(()->{
while(true){
String response = HttpUtil.get(url);
System.out.println("Response:" + response);
}
});
} catch (Exception e){
e.printStackTrace();
}
}
// 等待所有任务完成,这里设置了最长等待时间为1小时
try{
executorService.awaitTermination(1, TimeUnit.HOURS);
} catch (InterruptedException e){
// 如果当线程在等待是被中断,立即关闭线程池
System.out.println("线程池中断了,立即关闭");
executorService.shutdown();
}
// 关闭线程池
executorService.shutdown();;
}