go 利用orm簡單實現接口分布式鎖


在開發中有些敏感接口,例如用戶余額提現接口,需要考慮在並發情況下接口是否會發生問題。如果用戶將自己的多條提現請求同時發送到服務器,代碼能否扛得住呢?一旦沒做鎖,那么就真的會給用戶多次提現,給公司帶來損失。我來簡單介紹一下在這種接口開發過程中,我的做法。

 

第一階段:

我們使用的orm為xorm,提現表對應的結構體如下

type Participating struct {
	ID      uint          `xorm:"autoincr id" json:"id,omitempty"`
	Openid  string        `xorm:"openid" json:"openid"`
	Hit     uint          `xorm:"hit" json:"hit"`
	Orderid string        `xorm:"order_id" json:"order_id"`
	Redpack uint          `xorm:"redpack" json:"redpack"`
	Status  uint          `xorm:"status" json:"status"`
	Ctime   tool.JsonTime `xorm:"ctime" json:"ctime,omitempty"`
	Utime   tool.JsonTime `xorm:"utime" json:"utime,omitempty"`
	PayTime tool.JsonTime `xorm:"pay_time" json:"pay_time,omitempty"`
}

在Participating表中,是以Openid去重的,當一個Openid對應的Hit為1時,可以按照Redpack的數額提現,成功后將Status改為1,簡單來說這就是提現接口的業務邏輯。

起初我並沒有太在意並發的問題,我在MySQL的提現表中設置一個字段status來記錄提現狀態,我只是在提現時將狀態修改為2(體現中),提現完成后將status修改為1(已提現)。然后事實證明,我太天真了,用ab做了測試1s發送了1000個請求到服務器,結果。。。成功提現了6次。部分代碼如下

p_info := &Participating{}
// 查找具體提現數額 has, _ := db.Dalmore.Where("openid = ? and hit = 1 and status = 0", openid).Get(p_info) if !has { resp.Error(errcode.NO_REDPACK_FOUND, nil, nil) return } // 改status為提現中 p_info.Status = 2 db.Dalmore.Cols("status").Where("openid = ? and hit = 1 and status = 0", openid).Update(p_info) // 提現p_info.Redpack

 

第二階段:

既然出現了並發問題,那第一反應肯定的加鎖啊,代碼如下:

type Set struct {
	m map[string]bool
	sync.RWMutex
}

func New() *Set {
	return &Set{
		m: map[string]bool{},
	}
}

var nodelock = set.New()

// 加鎖
nodelock.Lock()

p_info := &Participating{}
// 查找具體提現數額
has, _ := db.Dalmore.Where("openid = ? and hit = 1 and status = 0", openid).Get(p_info)
if !has {
	resp.Error(errcode.NO_REDPACK_FOUND, nil, nil)
	return
}

// 改status為提現中
p_info.Status = 2
db.Dalmore.Cols("status").Where("openid = ? and hit = 1 and status = 0", openid).Update(p_info)

// 釋放鎖
nodelock.Unlock()

// 提現p_info.Redpack

  

加了鎖以后。。。emem,允許多次提現的問題解決了,但是這個鎖限制的范圍太多了,直接讓這段加鎖代碼變成串行,這大大降低了接口性能。而且,一旦部署多個服務端,這個鎖又會出現多次提現的問題,因為他只能攔住這一個服務的並發。看來得搞一個不影響性能的分布式才是王道啊。

 

第三階段:

利用redis,設置一個key為openid的分布式鎖,並設置一個過期時間可以解決當前的這個問題。但是難道就沒別的辦法了嗎?當然是有的,golang的xorm中Update函數其實是有返回值的:num,err,我就是利用num做了個分布式鎖。

//記錄update修改條數
num, err := db.Dalmore.Cols("status").Where("openid = ? and status = 0 and hit = 1", openid).Update(p_update)
if err != nil {
	logger.Runtime().Debug(map[string]interface{}{"error": err.Error()}, "error while updating")
	resp.Error(errcode.INTERNAL_ERROR, nil, nil)
	return
}

// 查看update操作到底修改了多少條數據,起到了分布式鎖的作用
if num != 1 {
	resp.Error(errcode.NO_REDPACK_FOUND, nil, nil)
	return
}

p_info := &Participating{}
_, err := db.Dalmore.Where("openid = ? and status = 2", openid).Get(p_info)
if err != nil {
	logger.Runtime().Debug(map[string]interface{}{"error": err.Error()}, "error while selecting")
	resp.Error(errcode.INTERNAL_ERROR, nil, nil)
	return
}

// 提現p_info.Redpack

  

其實有點投機取巧的意思,利用xorm的Update函數,我們將核對並發處理請求下數據准確性的問題拋給了MySQL,畢竟MySQL是經過千錘百煉的。再用ab測試,嗯,鎖成功了只有,只提現了一次,大功告成~

希望對大家有所幫助,祝大家每天開心~


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM