C# 使用缓存数据模拟抢购

 

  在所有的电商网站中,不乏大量的抢购,比如双十一,双十二等等,作为一名开发人员考虑最多的就是多并发以及高并发

  废话少说,开始写代码。我用了C#的MemoryCache代替试下流行的各种缓存

  商品测试类:

 1 public class ProductInfo
 2     {
 3         /// <summary>
 4         /// 商品Id
 5         /// </summary>
 6         public string ProductId { get; set; }
 7         /// <summary>
 8         /// 商品名称
 9         /// </summary>
10         public string ProductName { get; set; }
11         /// <summary>
12         /// 商品剩余数量
13         /// </summary>
14         public int TotalCount { get; set; }
15     }
View Code

  设置商品剩余数量缓存:

1 MemoryCache cache = MemoryCache.Default;
2             var model = new ProductInfo
3             {
4                 ProductId = Guid.NewGuid().ToString(),
5                 TotalCount = 10,
6                 ProductName = "XX商品名称"
7             };
8             cache.Set("Product", model, null, null);
9             MessageBox.Show("缓存设置完成!");
View Code

  模拟 15 个用户同时抢购:

 1 private void btnStart_Click(object sender, EventArgs e)
 2         {
 3             for (int i = 1; i <= 15; i++)
 4             {
 5                 Thread t = new Thread(ConsumeProduct);
 6                 t.Start(i);
 7             }
 8         }
 9         private void ConsumeProduct(object Id)
10         {
11             lock (this)
12             {
13                 MemoryCache cache = MemoryCache.Default;
14                 var model = cache["Product"] as ProductInfo;
15                 if (model.TotalCount > 0)
16                 {
17                     model.TotalCount -= 1;
18                     cache.Set("Product", model, null, null);
19                     Console.WriteLine($"使用数量1,剩余库存:{model.TotalCount},当前线程Id:{Id},当前时间:{DateTime.Now.ToString("ss:ffff")}");
20                 }
21                 else
22                     Console.WriteLine($"库存数量不足,剩余库存:{model.TotalCount},当前线程Id:{Id},当前时间:{DateTime.Now.ToString("ss:ffff")}");
23             }
24         }
View Code

  最后结果:

最后:抢购中最重要的是及时的进行数据更新,在更新的时候对事物进行加锁,防止多个线程对同一商品数量进行扣减,这仅仅是一个很简单的范例

猜你喜欢

转载自www.cnblogs.com/mybk/p/10097920.html