Springboot 自带请求实现多线程压测post get put 接口
Spring Boot默认使用的是Tomcat作为服务器容器,它本身就支持处理多线程请求。因此在Spring Boot中,无需额外配置即可实现多线程压测。
下面是一个简单的示例,演示如何使用Spring Boot进行多线程压测:
- 首先,创建一个Spring Boot项目,并添加以下依赖到
pom.xml文件中:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
</dependencies>
- 创建一个Controller类,定义需要测试的接口:
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TestController {
@GetMapping("/get")
public String get() {
// 处理GET请求
return "GET";
}
@PostMapping("/post")
public String post() {
// 处理POST请求
return "POST";
}
@PutMapping("/put")
public String put() {
// 处理PUT请求
return "PUT";
}
}
- 创建一个测试类,使用Apache HttpClient发送多线程请求:
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
public class LoadTest {
public static void main(String[] args) throws Exception {
CloseableHttpClient httpClient = HttpClients.createDefault();
int threadCount = 10; // 线程数
int requestCount = 100; // 每个线程的请求数
for (int i = 0; i < threadCount; i++) {
Thread thread = new Thread(() -> {
try {
for (int j = 0; j < requestCount; j++) {
// 发送GET请求
HttpGet httpGet = new HttpGet("http://localhost:8080/get");
HttpResponse response = httpClient.execute(httpGet);
// 处理响应结果
// 发送POST请求
HttpPost httpPost = new HttpPost("http://localhost:8080/post");
response = httpClient.execute(httpPost);
// 处理响应结果
// 发送PUT请求
HttpPut httpPut = new HttpPut("http://localhost:8080/put");
response = httpClient.execute(httpPut);
// 处理响应结果
}
} catch (Exception e) {
e.printStackTrace();
}
});
thread.start();
}
}
}
在上述测试类中,通过创建多个线程来模拟并发请求,每个线程发送一定数量的请求。
- 运行Spring Boot应用,并在控制台观察请求处理情况。
注意:在实际应用中,需要根据实际情况对线程数和请求数进行调整。此外,还需根据具体的压测需求,对请求的并发度、请求参数、请求头等进行相应的设置
原文地址: https://www.cveoy.top/t/topic/ic1D 著作权归作者所有。请勿转载和采集!