Elimizde şöyle bir kod olsun
private CompletableFuture<String> executeApiCallWithRetry(String url) {CompletableFuture<String> future = new CompletableFuture<>();executeApiCallWithRetryImpl(url, future, 0);return future;}private void executeApiCallWithRetryImpl(String url, CompletableFuture<String> future, int retryCount) {if (retryCount > MAX_RETRIES) {future.complete("Failed after maximum retries");return;}CompletableFuture.supplyAsync(() -> restTemplate.getForObject(url, String.class)).whenComplete((result, ex) -> {if (ex != null) {try {Thread.sleep(RETRY_INTERVAL_MS);} catch (InterruptedException e) {Thread.currentThread().interrupt();}executeApiCallWithRetryImpl(url, future, retryCount + 1); // Recursive call} else {future.complete(result);}});}
Şöyle yaparız
@Servicepublic class ApiService {@Autowiredprivate RestTemplate restTemplate;private static final int MAX_RETRIES = 3;private static final long RETRY_INTERVAL_MS = 1000;public List<String> executeParallelApiCalls() {List<String> urls = ...;List<CompletableFuture<String>> futures = urls.stream().map(url -> executeApiCallWithRetry(url)).collect(Collectors.toList()); // Wait for all operations to completeCompletableFuture<Void> allFutures = CompletableFuture.allOf(futures.toArray(new CompletableFuture[futures.size()])); // Convert result to listCompletableFuture<List<String>> result = allFutures.thenApply(v -> futures.stream().map(future -> future.getNow("Fallback result")).collect(Collectors.toList()));List<String> resultList = result.join();return resultList;}}
Hiç yorum yok:
Yorum Gönder