要实现库存更新与购物车同步,可以使用SignalR来实现实时通信。以下是一个简单的示例:
public class InventoryHub : Hub { // 更新库存信息 public void UpdateInventory(int productId, int quantity) { // 更新数据库中的库存信息 // 向所有客户端发送更新的库存信息 Clients.All.SendAsync("UpdateInventory", productId, quantity); } } const connection = new signalR.HubConnectionBuilder() .withUrl("/inventoryHub") .build(); connection.start().then(() => { console.log("Connected to InventoryHub"); connection.on("UpdateInventory", (productId, quantity) => { // 更新购物车信息 console.log(`Product ${productId} inventory updated to ${quantity}`); }); }).catch(err => console.error(err)); // 增加商品数量 function addToCart(productId) { // 更新库存数量 connection.invoke("UpdateInventory", productId, -1) .catch(err => console.error(err)); } // 减少商品数量 function removeFromCart(productId) { // 更新库存数量 connection.invoke("UpdateInventory", productId, 1) .catch(err => console.error(err)); } 通过以上步骤,就可以实现库存更新与购物车同步的功能。当用户修改购物车中商品数量时,库存信息会实时更新,确保购物车中的商品数量与库存信息保持同步。