From 9dd61913f7c37333692534a090db479d927fb025 Mon Sep 17 00:00:00 2001 From: michael <457813723@qq.com> Date: Wed, 10 Jul 2024 20:16:15 +0800 Subject: [PATCH] replace global lock to distributed lock --- http_server/handle/sub_account_init.go | 19 ++++++++++++++++--- http_server/handle/sub_account_init_free.go | 2 +- 2 files changed, 17 insertions(+), 4 deletions(-) diff --git a/http_server/handle/sub_account_init.go b/http_server/handle/sub_account_init.go index 4ac35f4..4eac8e5 100644 --- a/http_server/handle/sub_account_init.go +++ b/http_server/handle/sub_account_init.go @@ -2,6 +2,7 @@ package handle import ( "context" + "crypto/md5" "das_sub_account/config" "das_sub_account/internal" "das_sub_account/tables" @@ -20,6 +21,7 @@ import ( "net/http" "strings" "sync" + "time" ) type ReqSubAccountInit struct { @@ -322,12 +324,23 @@ func (h *HttpHandle) buildSubAccountInitTx(p *paramsSubAccountInitTx) (*txbuilde return &txParams, nil } -func (h *HttpHandle) getSvrBalance(p paramBalance) (uint64, []*indexer.LiveCell, error) { +func (h *HttpHandle) getSvrBalance(ctx context.Context, p paramBalance) (uint64, []*indexer.LiveCell, error) { if p.capacityForNeed == 0 { return 0, nil, fmt.Errorf("needCapacity is nil") } - svrBalanceLock.Lock() - defer svrBalanceLock.Unlock() + svrLockKey, _ := p.svrLock.Serialize() + lockKey := fmt.Sprintf("%x", md5.Sum(svrLockKey)) + if err := h.RC.Lock(lockKey, time.Second*5); err != nil { + return 0, nil, fmt.Errorf("get lock err") + } + defer func() { + if err := h.RC.UnLock(lockKey); err != nil { + log.Error(ctx, "UnLock err:", err.Error()) + } + }() + + //svrBalanceLock.Lock() + //defer svrBalanceLock.Unlock() liveCells, total, err := h.DasCore.GetBalanceCells(&core.ParamGetBalanceCells{ DasCache: h.DasCache, diff --git a/http_server/handle/sub_account_init_free.go b/http_server/handle/sub_account_init_free.go index 0c52dd3..c76d46a 100644 --- a/http_server/handle/sub_account_init_free.go +++ b/http_server/handle/sub_account_init_free.go @@ -87,7 +87,7 @@ func (h *HttpHandle) doSubAccountInitFree(ctx context.Context, req *ReqSubAccoun capacityNeed, capacityForChange := subAccountBasicCapacity+subAccountPreparedFeeCapacity+subAccountCommonFee, common.DasLockWithBalanceTypeMinCkbCapacity - change, liveCells, err := h.getSvrBalance(paramBalance{ + change, liveCells, err := h.getSvrBalance(ctx, paramBalance{ svrLock: h.ServerScript, capacityForNeed: capacityNeed, capacityForChange: capacityForChange,