import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.HashMap;
import java.util.Map;
public class ConcurrentPostRequestTest {
private static final String URL = "http://your-api-endpoint"; // 替换为你的API地址
private static final int CONCURRENT_REQUESTS = 1000; // 并发请求数量
private static RestTemplate restTemplate = new RestTemplate();
private static ExecutorService executorService = Executors.newFixedThreadPool(100); // 线程池大小
public static void main(String[] args) throws InterruptedException {
CompletableFuture<?>[] futures = new CompletableFuture[CONCURRENT_REQUESTS];
for (int i = 0; i < CONCURRENT_REQUESTS; i++) {
final String phone = "1234567890"; // 每个请求的phone参数值
futures[i] = CompletableFuture.runAsync(() -> {
try {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
Map<String, String> map = new HashMap<>();
map.put("phone", phone);
HttpEntity<Map<String, String>> request = new HttpEntity<>(map, headers);
ResponseEntity<String> response = restTemplate.postForEntity(URL, request, String.class);
System.out.println("Response status: " + response.getStatusCode() + ", Response body: " + response.getBody());
} catch (Exception e) {
System.err.println("Request failed: " + e.getMessage());
}
}, executorService);
}
// Wait for all futures to complete
CompletableFuture.allOf(futures).join();
// Shutdown the executor service
executorService.shutdown();
executorService.awaitTermination(1, TimeUnit.MINUTES);
}
}