6 Haziran 2023 Salı

CompletableFuture.supplyAsync metodu İle Retry

Örnek
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
@Service
public class ApiService {
  @Autowired
  private 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 complete
    CompletableFuture<Void> allFutures = CompletableFuture
      .allOf(futures.toArray(new CompletableFuture[futures.size()])); // Convert result to list
    CompletableFuture<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