下单调整分布式锁

This commit is contained in:
momo 2023-11-27 16:50:14 +08:00
parent db656bae90
commit 3212aef056

View File

@ -6,6 +6,7 @@ import (
"fusenapi/service/repositories"
"fusenapi/utils/auth"
"fusenapi/utils/basic"
"strconv"
"sync"
"time"
@ -35,8 +36,7 @@ func NewCreateOrderLogic(ctx context.Context, svcCtx *svc.ServiceContext) *Creat
// func (l *CreateOrderLogic) BeforeLogic(w http.ResponseWriter, r *http.Request) {
// }
var locks map[string]*sync.Mutex
var locksMutex sync.Mutex
var lockMap sync.Map
func (l *CreateOrderLogic) CreateOrder(req *types.CreateOrderReq, userinfo *auth.UserInfo) (resp *basic.Response) {
// 返回值必须调用Set重新返回, resp可以空指针调用 resp.SetStatus(basic.CodeOK, data)
@ -46,14 +46,21 @@ func (l *CreateOrderLogic) CreateOrder(req *types.CreateOrderReq, userinfo *auth
return resp.SetStatus(basic.CodeUnAuth)
}
// var lockKey string
// for _, v := range req.CartIds {
// var vStr = strconv.Itoa(int(v))
// lockKey = lockKey + "|" + vStr
// }
// // 分布式锁--防止重复下单
// LockWith(lockKey) //获取锁
// fmt.Println("获取到了锁")
var lockKey string
for _, v := range req.CartIds {
var vStr = strconv.Itoa(int(v))
lockKey = lockKey + "|" + vStr
}
// 分布式锁--防止重复下单
_, ok1 := lockMap.Load(lockKey) //获取锁
if ok1 {
basic.CodeApiErr.Message = "order creating"
return resp.SetStatusWithMessage(basic.CodeApiErr, "order creating, please waiting")
} else {
lockMap.Store(lockKey, true) //加锁
defer lockMap.Delete(lockKey) //释放锁
}
tPlus60Days := time.Now().AddDate(0, 0, 60).UTC()
res, err := l.svcCtx.Repositories.NewOrder.Create(l.ctx, &repositories.CreateReq{
@ -65,8 +72,6 @@ func (l *CreateOrderLogic) CreateOrder(req *types.CreateOrderReq, userinfo *auth
DeliveryMethod: constants.DELIVERYMETHODDSCLOUDSTORE,
})
// UnlockWith(lockKey) //释放锁
if err != nil {
return resp.SetStatus(&res.ErrorCode)
}
@ -92,27 +97,6 @@ func (l *CreateOrderLogic) CreateOrder(req *types.CreateOrderReq, userinfo *auth
})
}
func LockWith(resource string) {
locksMutex.Lock()
lock, ok := locks[resource]
if !ok {
lock = &sync.Mutex{}
locks[resource] = lock
}
locksMutex.Unlock()
lock.Lock()
}
func UnlockWith(resource string) {
locksMutex.Lock()
lock, ok := locks[resource]
if ok {
lock.Unlock()
}
locksMutex.Unlock()
}
// 处理逻辑后 w,r 如:重定向, resp 必须重新处理
// func (l *CreateOrderLogic) AfterLogic(w http.ResponseWriter, r *http.Request, resp *basic.Response) {
// // httpx.OkJsonCtx(r.Context(), w, resp)