秒杀系统防止库存超卖
第一种:通过数据库乐观锁实现(小型电商)
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(“商品已售罄”);
}
}
}