Go 庫存扣減的幾種實現方法
!!! 本篇文章只是簡單提供個實現的思路,如果你要用到生產環境,請自行優化方法。尤其多個微服務之間。!!!
這裡使用了 grpc、proto、gorm、zap、go-redis、go-redsync 等 package
Go Mutex 實現
var m sync.Mutex
func (*InventoryServer) LockSell(ctx context.Context, req *proto.SellInfo) (*emptypb.Empty, error) {
tx := global.DB.Begin()
m.Lock()
for _, good := range req.GoodsInfo {
var i model.Inventory
if result := global.DB.Where(&model.Inventory{Goods: good.GoodsId}).First(&i);
result.RowsAffected == 0 {
tx.Rollback() // 回滾
return nil, status.Errorf(codes.InvalidArgument, "未找到此商品的庫存資訊。")
}
if i.Stocks < good.Num {
tx.Rollback()
return nil, status.Errorf(codes.ResourceExhausted, "此商品的庫存不足")
}
i.Stocks -= good.Num
tx.Save(&i)
}
tx.Commit()
m.Unlock()
return &emptypb.Empty{}, nil
}
MySQL 悲觀鎖實現
func (*InventoryServer) ForUpdateSell(ctx context.Context, req *proto.SellInfo) (*emptypb.Empty, error) {
tx := global.DB.Begin()
for _, good := range req.GoodsInfo {
var i model.Inventory
if result := tx.Clauses(clause.Locking{
Strength: "UPDATE",
}).Where(&model.Inventory{Goods: good.GoodsId}).First(&i);
result.RowsAffected == 0 {
tx.Rollback()
return nil, status.Errorf(codes.InvalidArgument, "未找到此商品的庫存資訊。")
}
if i.Stocks < good.Num {
tx.Rollback()
return nil, status.Errorf(codes.ResourceExhausted, "此商品的庫存不足")
}
i.Stocks -= good.Num
tx.Save(&i)
}
tx.Commit()
return &emptypb.Empty{}, nil
}
MySQL 樂觀鎖實現
func (*InventoryServer) VersionSell(ctx context.Context, req *proto.SellInfo) (*emptypb.Empty, error) {
tx := global.DB.Begin()
for _, good := range req.GoodsInfo {
var i model.Inventory
for { // 併發請求相同條件比較多,防止放棄掉一些請求
if result := global.DB.Where(&model.Inventory{Goods: good.GoodsId}).First(&i);
result.RowsAffected == 0 {
tx.Rollback()
return nil, status.Errorf(codes.InvalidArgument, "未找到此商品的庫存資訊.")
}
if i.Stocks < good.Num {
tx.Rollback() // 回滾
return nil, status.Errorf(codes.ResourceExhausted, "此商品的庫存不足")
}
i.Stocks -= good.Num
version := i.Version + 1
if result := tx.Model(&model.Inventory{}).
Select("Stocks", "Version").
Where("goods = ? and version= ?", good.GoodsId, i.Version).
Updates(model.Inventory{Stocks: i.Stocks, Version: version});
result.RowsAffected == 0 {
zap.S().Info("庫存扣減失敗!")
} else {
break
}
}
}
tx.Commit() // 提交
return &emptypb.Empty{}, nil
}
Redis 分散式鎖實現
func (*InventoryServer) RedisSell(ctx context.Context, req *proto.SellInfo) (*emptypb.Empty, error) {
// redis 分散式鎖
pool := goredis.NewPool(global.Redis)
rs := redsync.New(pool)
tx := global.DB.Begin()
for _, good := range req.GoodsInfo {
mutex := rs.NewMutex(fmt.Sprintf("goods_%d", good.GoodsId))
if err := mutex.Lock(); err != nil {
return nil, status.Errorf(codes.Internal, "redis:分散式鎖獲取異常")
}
var i model.Inventory
if result := global.DB.Where(&model.Inventory{Goods: good.GoodsId}).First(&i); result.RowsAffected == 0 {
tx.Rollback()
return nil, status.Errorf(codes.InvalidArgument, "未找到此商品的庫存資訊")
}
if i.Stocks < good.Num {
tx.Rollback()
return nil, status.Errorf(codes.ResourceExhausted, "此商品的庫存不足")
}
i.Stocks -= good.Num
tx.Save(&i)
if ok, err := mutex.Unlock(); !ok || err != nil {
return nil, status.Errorf(codes.Internal, "redis:分散式鎖釋放異常")
}
}
tx.Commit()
return &emptypb.Empty{}, nil
}
測試
涉及到服務、資料庫等環境,此測試為虛擬碼
func main() {
var w sync.WaitGroup
w.Add(20)
for i := 0; i < 20; i++ {
go TestForUpdateSell(&w) // 模擬併發請求
}
w.Wait()
}
func TestForUpdateSell(wg *sync.WaitGroup) {
defer wg.Done()
_, err := invClient.Sell(context.Background(), &proto.SellInfo{
GoodsInfo: []*proto.GoodsInvInfo{
{GoodsId: 16, Num: 1},
//{GoodsId: 16, Num: 10},
},
})
if err != nil {
panic(err)
}
fmt.Println("庫存扣減成功")
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結