使用post请求模拟

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);
}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值