go 实现简单的加权分配
最近一段时间接手了一个golang编写的模块,从python转到golang这种静态语言还是有些不适应的,接手模块后的第一个需求是实现一个加权分配的方法。
简单来说数据库中存有3个链接,3个链接的权重比是1:2:3,当前端请求链接时,按照权重比,随机返回一个链接。无论那种语言,解决这个问题的思路都基本相同。我的思路是将权重相加,得到权重总和total,然后随机生成一个0~tatal之间的浮点数weight,根据weight在total中的分布对应链接的分布。
数据库Ad,表Adur,字段weight, url, is_del(标记删除),首先从数据库中读出is_del为0的所有数据,并求出weight总和,数据库操作使用go-xorm。
首先定义访问数据库的结构体
type Adurl struct {
ID uint `xorm:"autoincr id" json:"id"`
Weight float64 `xorm:"weight" json:"weight"`
Url string `xorm:"url" json:"url"`
Isdel uint `xorm:"is_del" json:"is_del"`
}
开始操作数据库
res := make([]Adurl, 0)
sum_res := new(Adurl)
db.Adurl.Where("is_del = 0").Find(&res)
total, err := db.Adurl.Where("is_del = 0").Sum(sum_res, "weight")
if err != nil {
logger.Runtime().Debug(map[string]interface{}{}, "failed to connect database")
}
生成随机浮点数weight
weight := rand.Float64() * total
接下来根据weight,遍历查库得到的res,来得出weight对应那个url
for _, a := range res {
if weight <= a.Weight {
return a.Url
} else {
weight -= a.Weight
}
}
浙公网安备 33010602011771号