httpclient 复用
All checks were successful
continuous-integration/drone Build is passing

This commit is contained in:
liukang 2025-03-04 23:47:49 +08:00
parent 5702612323
commit b987415fa2

View File

@ -24,6 +24,8 @@ import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* 定时任务调度测试
@ -269,7 +271,10 @@ public class RyTask {
List<MyReq> req = new ArrayList<>();
ExecutorService executorService = Executors.newFixedThreadPool(100);
HttpClient client = HttpClient.newHttpClient();
// 创建一个请求列表
List<CompletableFuture<String>> futures = new ArrayList<>();
for (Apply a : applies) {
// 准备JSON负载
@ -303,21 +308,26 @@ public class RyTask {
Thread.sleep(start - now - perform.getDelayTime());
log.info("抢票开始了");
for (MyReq r : req) {
// 发起异步请求但不等待结果
CompletableFuture<HttpResponse<String>> future2 = client.sendAsync(r.getRequest(), HttpResponse.BodyHandlers.ofString());
log.info("【用户】:" + r.getUser());
future2.thenAccept(response -> {
// 处理响应例如记录日志
log.info("Response received: " + response.statusCode());
log.info(response.body());
}).exceptionally(ex -> {
// 处理异常
ex.printStackTrace();
return null;
});
log.info("测试");
// 发起异步请求但不等待结果
CompletableFuture<String> future2 = client.sendAsync(r.getRequest(), HttpResponse.BodyHandlers.ofString())
.thenApplyAsync(HttpResponse::body, executorService);
futures.add(future2);
}
// 等待所有请求完成
CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();
// 输出所有请求的响应可选
for (CompletableFuture<String> future : futures) {
try {
System.out.println(future.get());
} catch (Exception e) {
log.error(e.getMessage());
}
}
// 关闭线程池
executorService.shutdown();
//status
Perform pStatus2 = new Perform();