[轉] 基於MySQL的秒殺核心設計(減庫存部分)-防超賣與高並發

來源:互聯網
上載者:User

標籤:

商品詳情頁面的靜態化,varnish加速,秒殺商品庫獨立部署伺服器這種就略過不講了。只討論庫存部分的最佳化

mysql配置層面的最佳化可以參考我的這篇文章 《關於mysql innodb引擎效能最佳化的一點心得》

重點設計在資料庫層面。

2張表:

第一張:判重表(buy_record),該使用者有沒秒殺過該商品

欄位: id, uid, goods_id, addtime

第二張表:商品表 goods

欄位: goods_id   goods_num

方案1:

start transaction;

select id from buy_record where uid=$uid and goods_id=$goods_id;

if(結果不為空白)

    拋異常,復原。

insert into buy_record。。。

if(受影響行數<=0)

    拋異常,復原。。。

select goods_num from goods where goods_id=$good_id;

if(庫存<=0)

    拋異常,復原。。。

update goods set goods_num=goods_num-1 where goods_id=$goods_id;

if(受影響行數<=0)

該方法在高並發下幾乎必然導致超賣。當庫存為1的時候剛好多個使用者同時 select goods_num from goods where goods_id=$good_id;此時庫存剛好大於0,做update操作的時候必然減到小於0.  同時上面進行是否秒殺過的判重同樣會出現類似問題

方案二:

start transaction;

select id from buy_record where uid=$uid and goods_id=$goods_id for  update ;

if(結果不為空白)

    拋異常,復原。

insert into buy_record。。。

if(受影響行數<=0)

    拋異常,復原。。。

select goods_num from goods where goods_id=$good_id for update ;

if(庫存<=0)

    拋異常,復原。。。

update goods set goods_num=goods_num-1  where goods_id=$goods_id ;

if(受影響行數<=0)

    拋異常,復原。。。

該方法有效防止了超賣,但是在每次select的時候加上了排它鎖,每次select操作都會被堵塞 ,並發效能大大降低。

方案三:    對(uid,goods_id)加唯一索引!!

start transaction;

insert into buy_record。。。

if(唯一索引報錯?)

    拋異常,已經秒過了,復原。。。

update goods set goods_num=goods_num-1  where goods_id=$goods_id and goods_num>0 ;

if(受影響行數<=0)

    拋異常,商品秒完了,復原。。。

該方法完美的解決了超賣與select排它鎖導致的並發低的問題,並且4個sql縮減成2個sql語句。極大提升效能

From: http://www.tuicool.com/articles/Bfa63e6

 

[轉] 基於MySQL的秒殺核心設計(減庫存部分)-防超賣與高並發

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.