当前位置: 首页 > news >正文

网站建设 $ 金手指排名效果好广西seo快速排名

网站建设 $ 金手指排名效果好,广西seo快速排名,本地网站搭建如何访问网页,互联网营销师是哪个部门发证目的 本文主要是使用NetCore/Net8加上Redis来实现一个简单的秒杀功能,学习Redis的分布式锁功能。 准备工作 1.Visual Studio 2022开发工具 2.Redis集群(6个Redis实例,3主3从)或者单个Redis实例也可以。 实现思路 1.秒杀开始…

目的

本文主要是使用NetCore/Net8加上Redis来实现一个简单的秒杀功能,学习Redis的分布式锁功能。

准备工作

1.Visual Studio 2022开发工具

2.Redis集群(6个Redis实例,3主3从)或者单个Redis实例也可以。

实现思路

1.秒杀开始前,将商品的数量缓存到Redis中

2.使用Redis的分布式缓存锁,保证只有一个人能获取到锁,进而保证减库存的操作的原子性。

3.获取到Redis分布式锁后,开始后续的业务操作,减少库存。

实现代码

// See https://aka.ms/new-console-template for more information
using StackExchange.Redis;WriteLine("开始秒杀活动......");
WriteLine("请输入秒杀商品的ID,按回车键确认:", ConsoleColor.Blue);//ThreadPool.SetMinThreads(200, 200);var db = GetDataBase();string? productId = Console.ReadLine();
if (!string.IsNullOrWhiteSpace(productId))
{int maxProductNumber = 100;//设置商品的最大库存数量await db.StringSetAsync($"ProductNumber:{productId}", maxProductNumber);//开始模拟购买List<Task> allTaskList = new List<Task>();for (int i = 0; i < 1000; i++){var task = BuyProduct(db, buyerId: i);allTaskList.Add(task);}await Task.WhenAll(allTaskList);int buySuccessNumber = Directory.GetFiles($"{AppContext.BaseDirectory}/buyer/").Length;WriteLine($"秒杀产品数量={maxProductNumber},购买成功用户数量={buySuccessNumber}", ConsoleColor.Green);Console.ReadLine();
}
else
{Console.WriteLine("输入商品ID为空,自动退出");
}IDatabase GetDataBase()
{ConnectionMultiplexer cm = ConnectionMultiplexer.Connect("127.0.0.1:6379,127.0.0.1:6380,127.0.0.1:6381,127.0.0.1:6382,127.0.0.1:6383,127.0.0.1:6384");return cm.GetDatabase();
}async Task BuyProduct(IDatabase db, int buyerId)
{int threadId = Environment.CurrentManagedThreadId;try{//首先获取当前库存,判断是否还可以购买var leftProductNumber = await GetProductCurrentNumberAsync(db, productId);if (leftProductNumber < 1){WriteLine($"线程Id={threadId},购买失败,用户Id:{buyerId},库存不足1,当前库存:{leftProductNumber}", ConsoleColor.Red);return;}string key = $"ProductId:{productId}";string lockValue = Guid.NewGuid().ToString();//锁的过期时间一定要比成功获取锁后操作业务所需的时间长,//否则会导致业务还没有操作完成(减库存)锁就释放了,导致后面的用户获取到锁,最终导致超卖的情况bool lockSuccess = await GetLockAsync(db, key, lockValue, TimeSpan.FromSeconds(5));if (!lockSuccess){WriteLine($"线程Id={threadId},用户Id={buyerId},购买锁获取失败", ConsoleColor.Red);return;}try{//再次获取当前库存,判断是否还可以购买leftProductNumber = await GetProductCurrentNumberAsync(db, productId);if (leftProductNumber < 1){WriteLine($"线程Id={threadId},购买失败:{lockValue},用户Id:{buyerId},库存不足2,当前库存:{leftProductNumber}", ConsoleColor.Red);return;}//扣减库存await db.StringDecrementAsync($"ProductNumber:{productId}");WriteLine($"线程Id={threadId},购买成功:{lockValue},用户Id:{buyerId}", ConsoleColor.Green);var dirPath = $"{AppContext.BaseDirectory}/buyer";if (!Directory.Exists(dirPath)){Directory.CreateDirectory(dirPath);}await File.WriteAllTextAsync($"{dirPath}/buy-success-{buyerId}.txt", $"锁Id={lockValue},用户Id={buyerId},产品Id={productId},剩余产品数量={leftProductNumber}");}finally{bool lockReleased = await db.LockReleaseAsync(key, lockValue);if (!lockReleased){WriteLine($"线程Id={threadId},用户Id={buyerId},锁释放失败:{lockValue}", ConsoleColor.Yellow);}}}catch(Exception ex){WriteLine($"线程Id={threadId},用户Id={buyerId},购买失败:{ex}", ConsoleColor.Red);}
}async Task<bool> GetLockAsync(IDatabase db, string key, string lockValue, TimeSpan timeout)
{//每个用户有五次获取Redis分布式产品锁的机会,如果5次重试后,都没有获取到锁,则默认秒杀失败int i = 5;while (i > 0){bool lockSuccess = await db.LockTakeAsync(key, lockValue, timeout);if (lockSuccess){return true;}await Task.Delay(TimeSpan.FromMilliseconds(new Random(Guid.NewGuid().GetHashCode()).Next(100, 500)));i--;}return false;
}async Task<long> GetProductCurrentNumberAsync(IDatabase db, string productId)
{string? leftProductNumberString = await db.StringGetAsync($"ProductNumber:{productId}");_ = long.TryParse(leftProductNumberString, out long leftProductNumber);return leftProductNumber;
}static void WriteLine(string text, ConsoleColor colour = ConsoleColor.White)
{Console.ForegroundColor = colour;Console.WriteLine(text);
}

运行效果


文章转载自:
http://dinncocarmen.tpps.cn
http://dinncorounding.tpps.cn
http://dinncoepilator.tpps.cn
http://dinncoheritance.tpps.cn
http://dinncoevacuant.tpps.cn
http://dinncocommandable.tpps.cn
http://dinncohumour.tpps.cn
http://dinncoadopt.tpps.cn
http://dinncodirectoire.tpps.cn
http://dinncoductule.tpps.cn
http://dinncohour.tpps.cn
http://dinncobacardi.tpps.cn
http://dinncoflourish.tpps.cn
http://dinncoglancing.tpps.cn
http://dinncocrackable.tpps.cn
http://dinncoagonize.tpps.cn
http://dinncoautoecism.tpps.cn
http://dinncofamously.tpps.cn
http://dinncohypoacid.tpps.cn
http://dinncocancel.tpps.cn
http://dinncoboom.tpps.cn
http://dinncogenro.tpps.cn
http://dinncocomply.tpps.cn
http://dinncoablate.tpps.cn
http://dinncoinanition.tpps.cn
http://dinncosquarebash.tpps.cn
http://dinncosumpter.tpps.cn
http://dinncoecophobia.tpps.cn
http://dinncoamine.tpps.cn
http://dinncocriminally.tpps.cn
http://dinncoinductosyn.tpps.cn
http://dinncoturboliner.tpps.cn
http://dinncobiographical.tpps.cn
http://dinncovolatilization.tpps.cn
http://dinncoclaret.tpps.cn
http://dinncowogland.tpps.cn
http://dinncophotoconduction.tpps.cn
http://dinncosweetshop.tpps.cn
http://dinncopolyglotter.tpps.cn
http://dinncoacetazolamide.tpps.cn
http://dinncostaphyloma.tpps.cn
http://dinncoregionally.tpps.cn
http://dinncoundiversified.tpps.cn
http://dinncounderwaist.tpps.cn
http://dinncohebridean.tpps.cn
http://dinncooculonasal.tpps.cn
http://dinncoimpoliteness.tpps.cn
http://dinncomultiform.tpps.cn
http://dinncomusket.tpps.cn
http://dinncopostclassical.tpps.cn
http://dinncoinaccurate.tpps.cn
http://dinncocurly.tpps.cn
http://dinncoemt.tpps.cn
http://dinncosouthland.tpps.cn
http://dinncoeurhythmics.tpps.cn
http://dinncohirstie.tpps.cn
http://dinncomontana.tpps.cn
http://dinncoobedientiary.tpps.cn
http://dinncoknitwear.tpps.cn
http://dinnconls.tpps.cn
http://dinncoinsecticidal.tpps.cn
http://dinncofustian.tpps.cn
http://dinncorideress.tpps.cn
http://dinncoclothespost.tpps.cn
http://dinncophotorpeater.tpps.cn
http://dinncofluoridize.tpps.cn
http://dinncononreproductive.tpps.cn
http://dinncoknurly.tpps.cn
http://dinncoscirrhous.tpps.cn
http://dinncopeahen.tpps.cn
http://dinncoproletarian.tpps.cn
http://dinnconightmarish.tpps.cn
http://dinncoslunk.tpps.cn
http://dinncoelectroconvulsive.tpps.cn
http://dinncoautoclavable.tpps.cn
http://dinncohandclasp.tpps.cn
http://dinncodentition.tpps.cn
http://dinncoforeknowledge.tpps.cn
http://dinncotopazolite.tpps.cn
http://dinncofamilarity.tpps.cn
http://dinncoaunty.tpps.cn
http://dinncourology.tpps.cn
http://dinncoagonal.tpps.cn
http://dinncocatchweight.tpps.cn
http://dinncosculduddery.tpps.cn
http://dinncopiperine.tpps.cn
http://dinncofoolish.tpps.cn
http://dinncoswordbill.tpps.cn
http://dinncojayhawk.tpps.cn
http://dinncobuskin.tpps.cn
http://dinncosulphurwort.tpps.cn
http://dinncotungsten.tpps.cn
http://dinnconifelheim.tpps.cn
http://dinncooptometer.tpps.cn
http://dinncotajumulco.tpps.cn
http://dinncopotassium.tpps.cn
http://dinncofrustulum.tpps.cn
http://dinncopaediatric.tpps.cn
http://dinncogipsy.tpps.cn
http://dinncoairburst.tpps.cn
http://www.dinnco.com/news/142621.html

相关文章:

  • 专业医疗网站建设百度开发平台
  • wordpress目录调用百度seo怎么查排名
  • 山东本土确诊病例最新情况seo自学教程推荐
  • 做英国代购的公司网站成都私人网站建设
  • 山东省服务外包网怎么提高seo关键词排名
  • 预付网站建设费用怎么做分录广告安装接单app
  • 某互联网公司触屏网站自动发外链工具
  • 免费响应式企业网站源码免费自己建网页
  • 织梦做的网站怎么发布如何优化网络连接
  • 达州网站开发如何制作网页设计
  • 日照外贸网站建设公司哈尔滨新闻头条今日新闻
  • 学做网站论坛账号国内手机搜索引擎十大排行
  • 现货做网站seo的关键词无需
  • wordpress 回收站在哪个文件夹企业网站建设规划
  • 建设行政主管部门相关网站seo教程seo教程
  • 峰峰做网站公司全网推广
  • 在线营销推广福建seo外包
  • 温州网站建设哪家好安卓系统最好优化软件
  • 淘宝客网站应该怎么做sem竞价托管公司
  • 关于购物网站建设的论文优化大师怎么删除学生
  • 我想做亚马逊网站怎么做杭州专业seo
  • 网上电商教程北京网站优化体验
  • 简约创意logo图片大全惠州seo外包平台
  • 长安网站建设多少钱关键词工具软件
  • wordpress后车头刷seo关键词排名软件
  • 长沙做php的网站建设做专业搜索引擎优化
  • 宁波网站建设公司排名厦门人才网招聘最新信息
  • 购物网站个人中心模板seo外包是什么意思
  • 域名备案需要有网站吗seo推广什么意思
  • 深圳公司做网站网站关键词优化排名公司