秒殺系統防止庫存超賣


第一種:通過數據庫樂觀鎖實現(小型電商)

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("商品已售罄");
}
}
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM