第一种:通过数据库乐观锁实现(小型电商)

update productstocks set realstock=realstock-#{buys} where sku = #{sku} and realstock-#{buys}>=0

根据受影响的行数判断是否执行成功

大型互联网不是这么玩的
数据库有瓶颈
第二种:使用redis 分布式锁实现

var resource = “the-thing-we-are-locking-on”;
var expiry = TimeSpan.FromSeconds(5);
var wait = TimeSpan.FromSeconds(10);
var retry = TimeSpan.FromSeconds(1);
string sku = “001”;

using (var redLock = RedisHelper.RedlockFactory.CreateLock(resource, expiry, wait, retry)) // there are also non async Create() methods
{
if (redLock.IsAcquired)
{
var r = RedisHelper.StringGet(sku);
var num = new Random().Next(1, 10);

if (Convert.ToInt32(r) >= num)
{
RedisHelper.StringDecrement(sku, num);
}
else
{
throw new Exception(“商品已售罄”);
}
}
}

版权声明:本文为yxlblogs原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/yxlblogs/p/9149825.html