在CompletableFuture.allof中处理超时并记录超时期货的正确方法

问题描述 投票:1回答:1

我的ItemDetails和ItemPriceDetails定义如下 -

class ItemDetails {
  private int itemId;
  private int uom;
  private int zipcode;
  private String promoCode;
}

class ItemPriceDetails {
  private int itemId;
  private int uom;
  private int zipcode;
  private float totalCost;
  private float totalTax;
  private TaxDetails taxDetails;
  private DiscountDetails discountDetails;
}

InventoryTargetExecutors是第三方jar,它提供fetchPrice函数,它将ItemDetails作为输入并返回CompletableFuture<ItemPriceDetails>作为输出。

我想使用具有指定超时的CompletableFuture.allof函数并行调用多个InventoryTargetExecutors,并在调用期间打印timedout的InventoryTargetExecutors

ItemDetails  ids = ...;
List<InventoryConfigExecutors> inventoryConfigExecutors = applicationContext.get("InventoryConfigExecutors");
List<CompletableFuture<Pair<ItemPriceDetails, InventoryConfigExecutors>>> priceFutures =  inventoryConfigExecutors.stream().map(ice -> Pair.of(ice.fetchPrice(ids), ice)).collect(Collectors.toList());
CompletableFuture<Void> futuresExecuted = CompletableFuture.allOf(priceFutures.toArray(new CompletableFuture[priceFutures.size()]));

我不知道如何使用CompletableFuture.allof超时priceFutures,同时记录超时的InventoryConfigExecutors。

java java-8 completable-future
1个回答
0
投票

如果使用JDK 9或更高版本,CompletableFuture.orTimeout将允许您设置超时。对于早期版本,您需要自己实现,可能通过调度调用completeExceptionally的任务。

对于日志记录,您可以使用whenComplete并检查throwable参数,记录它是否存在。注意:这不区分超时或其他故障。

© www.soinside.com 2019 - 2024. All rights reserved.