我有几个异步 api 调用组合在一起形成一个完整的 futures 链。链的每个部分都取决于前一阶段,即如果前一个调用返回非空数据,则我们跳过下一个调用。
我不仅想测量整个链执行所花费的总时间,还想单独测量每个 api 调用。
像下面的代码片段那样测量时间是否正确,或者有更好的方法来做到这一点,例如扩展
CompletableFuture
类?
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
public class CompletableFutureChainExample {
public static void main(String[] args) {
// Record the start time
long startTime = System.nanoTime();
CompletableFuture<String> futureChain = CompletableFuture.supplyAsync(() -> api1Call())
.thenCompose(result -> {
long api2StartTime = System.nanoTime();
if (api1Call.isEmpty()) {
CompletableFuture<String> api2Call = api2Call(result);
} else {
return CompletableFuture.completedFuture(api1Call);
}
long api2ElapsedTime = (System.nanoTime() - api2StartTime) / 1_000_000; // Convert to milliseconds
System.out.println("Api 2 Elapsed Time: " + api2ElapsedTime + " milliseconds");
return api2Result;
})
.thenCompose(result -> {
long api3StartTime = System.nanoTime();
if (api2Call.isEmpty()) {
CompletableFuture<String> api3Call = api3Call(result);
} else {
return CompletableFuture.completedFuture(api2Call);
}
long api3ElapsedTime = (System.nanoTime() - api3StartTime) / 1_000_000; // Convert to milliseconds
System.out.println("Api 3 Elapsed Time: " + api3ElapsedTime + " milliseconds");
return api3Result;
})
.thenApply(result -> finalMapping(result));
// Wait for the last CompletableFuture in the chain to complete
try {
String finalResult = futureChain.get();
// Calculate the total elapsed time
long totalElapsedTime = (System.nanoTime() - startTime) / 1_000_000; // Convert to milliseconds
System.out.println("Final Result: " + finalResult);
System.out.println("Total Elapsed Time: " + totalElapsedTime + " milliseconds");
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
private static CompletableFuture<String> api1Call(String input) {
// some time-consuming computation
return CompletableFuture.completedFuture(“whatever1”);
}
private static CompletableFuture<String> api2Call(String input) {
// some time-consuming computation
return CompletableFuture.completedFuture(“whatever2”);
}
private static CompletableFuture<String> api3Call(String input) {
// some time-consuming computation
return CompletableFuture.completedFuture(“whatever3”);
}
private static CompletableFuture<String> finalMapping(String input) {
// mapping
return CompletableFuture.completedFuture(“whateverFinal”);
}
}