import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
public class EcommerceSystem {
// 模拟库存查询服务
public static CompletableFuture<Integer> queryStock() {
return CompletableFuture.supplyAsync(() -> {
// 实际业务逻辑,这里模拟返回库存数量
return 100;
});
}
// 模拟价格计算服务
public static CompletableFuture<Double> calculatePrice() {
return CompletableFuture.supplyAsync(() -> {
// 实际业务逻辑,这里模拟返回价格
return 99.99;
});
}
public static CompletableFuture<String> process() {
return queryStock()
.thenCombine(calculatePrice(), (stock, price) -> {
// 整合库存和价格信息
return "库存数量: " + stock + ", 价格: " + price;
})
.handle((result, ex) -> {
if (ex != null) {
// 处理异常,返回错误信息
return "服务调用失败: " + ex.getMessage();
}
return result;
});
}
public static void main(String[] args) {
try {
String response = process().get();
System.out.println(response);
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
}