mysql乐观锁实现思路
go使用乐观锁实现分布式锁
func (*InventoryServer) Sell(ctx context.Context, req *proto.SellInfo) (*emptypb.Empty, error) {
var inv model.Inventory
var details []model.GoodsDetail
//一个订单可以购买多个商品
//req.GoodsInfo 多件商品 同时减库存
for _, goodInfo := range req.GoodsInfo {
details = append(details, model.GoodsDetail{
Goods: goodInfo.GoodsId,
Num: goodInfo.Num,
})
//如果没有更新成功一直重试
for true {
if result := global.DB.Where(&model.Inventory{Goods: goodInfo.GoodsId}).First(&inv); result.RowsAffected == 0 {
return nil, status.Errorf(codes.InvalidArgument, "没有库存信息")
}
//判断库存是否充足
if inv.Stocks < goodInfo.Num {
return nil, status.Errorf(codes.ResourceExhausted, "库存不足")
}
//扣减, 会出现数据不一致的问题 - 锁,分布式锁
tx := global.DB.Select("stocks", "version").Where("goods = ?", goodInfo.GoodsId).Where("version = ?", inv.Version).Updates(model.Inventory{Stocks: inv.Stocks - 1, Version: inv.Version + 1})
if tx.RowsAffected == 1 {
break
}
}
}
return &emptypb.Empty{}, nil
}