在本教程中,我们将比较 Java 19 的虚拟线程与 Reactor 项目的 WebFlux。我们将首先回顾每种方法的基本工作原理,然后分析它们的优势和劣势。
我们将从探索响应式框架的优势开始,并看看为什么 WebFlux 仍然具有价值。之后,我们将讨论每个请求一个线程的方法,并强调虚拟线程可能是更好选择的场景。
2. 代码示例
在本文的代码示例中,我们假设我们正在开发一个电子商务应用程序的后端。我们将专注于负责计算和发布添加到购物车中的商品价格的函数:
class ProductService {
private final String PRODUCT_ADDED_TO_CART_TOPIC = "product-added-to-cart";
private final ProductRepository repository;
private final DiscountService discountService;
private final KafkaTemplate`<String, ProductAddedToCartEvent>` kafkaTemplate;
// 构造函数
public void addProductToCart(String productId, String cartId) {
Product product = repository.findById(productId)
.orElseThrow(() -> new IllegalArgumentException("not found!"));
Price price = product.basePrice();
if (product.category().isEligibleForDiscount()) {
BigDecimal discount = discountService.discountForProduct(productId);
price.setValue(price.getValue().subtract(discount));
}
var event = new ProductAddedToCartEvent(productId, price.getValue(), price.getCurrency(), cartId);
kafkaTemplate.send(PRODUCT_ADDED_TO_CART_TOPIC, cartId, event);
}
}
大约 6 分钟