import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
public class EcommerceSystem {
// 模拟根据用户ID查询购物车商品列表的异步操作
public static CompletableFuture<String> queryCartItems(String userId) {
return CompletableFuture.supplyAsync(() -> {
// 这里模拟查询操作,可能会失败
if (Math.random() < 0.5) {
throw new RuntimeException("查询购物车商品列表失败");
}
return "商品1,商品2,商品3";
});
}
// 模拟根据购物车商品列表计算总价的异步操作
public static CompletableFuture<Double> calculateTotalPrice(String cartItems) {
return CompletableFuture.supplyAsync(() -> {
// 这里模拟计算操作,可能会失败
if (Math.random() < 0.5) {
throw new RuntimeException("计算总价失败");
}
return 100.0;
});
}
public static void main(String[] args) {
String userId = "12345";
CompletableFuture<Double> future = queryCartItems(userId)
.thenCompose(EcommerceSystem::calculateTotalPrice)
.exceptionally(ex -> {
System.out.println("发生异常: " + ex.getMessage());
return -1.0; // 返回一个默认值表示失败
});
try {
double totalPrice = future.get();
if (totalPrice != -1.0) {
System.out.println("总价: " + totalPrice);
}
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
}