分佈式鎖實現方案優缺點分析
項目修改 :
項目中用的是數據庫分佈式鎖,但會造成大量數據堆積在數據庫update這裏,將壓力分給業務層。
<update id="decreaseItemSpecStock">
update
items_spec
set
stock = stock - #{pendingCounts}
where
id = #{specId}
and
stock >= #{pendingCounts}
</update>
public void decreaseItemSpecStock(String specId, int buyCounts) {
RLock lock = redissonClient.getLock("Item_LOck" + specId);
lock.lock(5, TimeUnit.SECONDS);
try {
int result = itemsMapperCustom.decreaseItemSpecStock(specId, buyCounts);
if(result !=1){
throw new RuntimeException("庫存不足");
}
}catch (RuntimeException e){
throw e;
}
lock.unlock();
}