springboot 使用线程池进行批量网络请求代码示例
时间: 2023-04-04 22:02:32 浏览: 109
以下是使用线程池进行批量网络请求的 Spring Boot 代码示例:
```java
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
@Component
public class BatchRequestService {
private final RestTemplate restTemplate;
private final ThreadPoolTaskExecutor executor;
public BatchRequestService(RestTemplate restTemplate, ThreadPoolTaskExecutor executor) {
this.restTemplate = restTemplate;
this.executor = executor;
}
public List<String> batchRequest(List<String> urls) throws ExecutionException, InterruptedException {
CompletableFuture<String>[] futures = new CompletableFuture[urls.size()];
for (int i = 0; i < urls.size(); i++) {
String url = urls.get(i);
futures[i] = CompletableFuture.supplyAsync(() -> restTemplate.getForObject(url, String.class), executor);
}
CompletableFuture.allOf(futures).join();
return CompletableFuture.allOf(futures)
.thenApply(v -> {
return CompletableFuture.completedFuture(futures)
.thenApply(f -> {
return f[0].join() + f[1].join() + f[2].join();
});
}).get();
}
}
```
这个示例使用了 Spring Boot 的线程池任务执行器 ThreadPoolTaskExecutor 来执行批量网络请求,使用 CompletableFuture 来处理异步请求结果。
阅读全文