23 Mart 2022 Çarşamba

CompletableFuture.completedFuture - İşin Belirtilen Değer İle Bitmesini Sağlar

Giriş
Factory metodudur. "Completed" bir CompletableFuture nesnesi döner yani isDone () metodu true olur. Açıklaması şöyle.
Creates an already completed CompletableFuture with a predefined result. Usually, this may act as the starting stage in your computation.
CompletableFuture.completed() ile aynı şeydir. Farklı olarak bu metod CompletableFuture döner. complete() metodunun imzası şöyle
public boolean complete(T value)
completedFuture () metodunun imzası şöyle
public static <U> CompletableFuture<U> completedFuture(U value)
Örnek
Şöyle yaparız.
List<String> userList = ...
CompletableFuture<List<String>> f = CompletableFuture.completedFuture(userList);
Örnek
Bir Stream'i kendi ExecutorService nesnemiz ile paralel olarak çalıştırmak için şöyle yaparız.
public static CompletableFuture<Void> performAllItemsBackup(Stream<Item> items) {
  ExecutorService pool = Executors.newFixedThreadPool(3);
  try {
    return CompletableFuture.allOf(
      items.map(CompletableFuture::completedFuture)
           .map(f -> f.thenAcceptAsync(performSingleItemBackup, pool))
           .toArray(CompletableFuture<?>[]::new));
  } finally {
    pool.shutdown();
  }
}
Örnek
Feign Client çağrılarını asenkron yapmak için şöyle yaparız. Elimizde senkron bir Feign Client olsun
@FeignClient(url = "${external.resource.base}", name = "external")
public interface ExternalFeignClient {

  @GetMapping(value = "${external.resource.records}", produces = "application/json")
  @Headers({ACCEPT_APPLICATION_JSON, CONTENT_TYPE_APPLICATION_JSON})
  ResponseWrapper<Record> getRecords(@RequestHeader Map<String, String> header,
                                     @RequestParam Map<String, String> queryMap,
                                     @RequestParam("limit") Integer limit,
                                     @RequestParam("offset") Integer offset);


}

@Service
public class ExternalFeignClientAsync {
  
  @Awtowired
  private ExternalFeignClient externalFeignClient;

  @Async
  CompletableFuture<ResponseWrapper<Record>> getRecordsAsync(Map<String, String> header,
                                                             Map<String, String> header,
                                                             Integer limit,
                                                             Integer offset){
    CompletableFuture.completedFuture(externalFeignClient.getRecords(header,header,
      limit,offset));
  }
}
Hepsini asenkron çağırmak için şöyle yaparız
@Service
public class ExternalService {
  
  @Autowired
  private ExternalFeignClientAsync externalFeignClientAsync;
  
  List<Record> getAllRecords() {
    
    final AtomicInteger offset = new AtomicInteger();
    int pageSize = properties.getPageSize(); // set this as you wish
    int batches = (totalCount / pageSize) + (totalCount % pageSize > 0 ? 1 : 0);
    return IntStream.range(0, batches)
      .parallel()
      .mapToObj(i -> {
        final int os = offset.getAndAdd(pageSize);
        return externalFeignClientAsync.getRecordsAsync(requestHeader, queryMap,
          fetchSize, os);
      })
      .map(CompletableFuture::join)
      .map(ResponseWrapper::getItems)
      .flatMap(List::stream)
      .toList();
  }
}



Hiç yorum yok:

Yorum Gönder