推薦在數(shù)據(jù)庫(kù)中處理坯苹,適合分布式場(chǎng)景
用數(shù)據(jù)庫(kù)行鎖去限制隆檀,
String goodsId = "商品id";
int num = "本次需要扣減的庫(kù)存量";
// count表示影響行數(shù)
int count = (update t_goods set num = num - #{num} where goods_id = #{goodsId} and num - #{num} >= 0);
// count = 1,表示扣減成功粹湃,否則扣減失敗
if(count==1){
//扣減庫(kù)存成功
}else{
//扣減庫(kù)存失敗
}
SHOW VARIABLES LIKE 'innodb_lock_wait_timeout'; 事務(wù)默認(rèn)超時(shí)時(shí)間是50秒
1恐仑、排他鎖
image.png
image.png
如果將mapper里面的代碼換成 for update
當(dāng)一個(gè)線程走到55行的時(shí)候,另一個(gè)線程走到53行就會(huì)報(bào)如下錯(cuò)誤
image.png
2为鳄、共享鎖
image.png
image.png
【共享鎖可以防止在查詢過(guò)程中數(shù)據(jù)被意外修改裳仆,有助于維護(hù)數(shù)據(jù)的完整性」虑眨】【可以并發(fā)讀】
如果將mapper里面的代碼換成 lock in share mode
當(dāng)一個(gè)線程走到55行的時(shí)候歧斟,另一個(gè)線程也走到55行就會(huì)報(bào)如下錯(cuò)誤
image.png
多線程調(diào)試看這個(gè)http://www.reibang.com/p/22dc499ef1f8