用于以预定义比率循环服务器的 Go 算法

我正在尝试制作一种算法,该算法可以按预定义的比率循环真实事物,在我的情况下是后端服务器。


例如我有 2 个后端服务器


type server struct {

    addr string

    ratio float64

    counter int64

}


// s2 is a beast and may handle 3 times the requests then s1 *edit

s1 := &server{":3000", 0.25}

s2 := &server{":3001", 0.75}


func nextServer() {

    server := next() // simple goroutine that provides the next server between s1 and s2

    N := server.counter / i

    if float64(N) > server.ratio {

        //repeat this function

        return nextServer()

    }


    server.counter += 1

}    


for i := 0; i < 1000; i++ {

    nextServer()

}

s1 有 250 作为计数器(处理的请求)

s2 很大,所以他有 750 作为计数器(请求处理)

这是我得到的一个非常简单的实现,但是当我像 10000 时,它会在 nextServer() 中不断循环,因为 N 总是 > server.ratio。


只要我在 5000 左右,它就完美无缺。但我认为有更好的算法来循环比率。


如何使这个简单而扎实?


江户川乱折腾
浏览 180回答 1
1回答

喵喵时光机

像这样的东西?package mainimport (&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "math/rand")type server struct {&nbsp; &nbsp; addr&nbsp; string&nbsp; &nbsp; ratio float64}var servers []serverfunc nextServer() *server {&nbsp; &nbsp; rndFloat := rand.Float64() //pick a random number between 0.0-1.0&nbsp; &nbsp; ratioSum := 0.0&nbsp; &nbsp; for _, srv := range servers {&nbsp; &nbsp; &nbsp; &nbsp; ratioSum += srv.ratio //sum ratios of all previous servers in list&nbsp; &nbsp; &nbsp; &nbsp; if ratioSum >= rndFloat { //if ratiosum rises above the random number&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return &srv //return that server&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return nil //should not come here}func main() {&nbsp; &nbsp; servers = []server{server{"0.25", 0.25}, server{"0.50", 0.50},&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; server{"0.10", 0.10}, server{"0.15", 0.15}}&nbsp; &nbsp; counts := make(map[string]int, len(servers))&nbsp; &nbsp; for i := 0; i < 100; i++ {&nbsp; &nbsp; &nbsp; &nbsp; srv := nextServer()&nbsp; &nbsp; &nbsp; &nbsp; counts[srv.addr] += 1&nbsp; &nbsp; }&nbsp; &nbsp; fmt.Println(counts)}产量例如:map[0.50:56 0.15:15 0.25:24 0.10:5]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go