github.com/fufuok/balancer@v1.0.0/examples/default/main.go (about) 1 package main 2 3 import ( 4 "fmt" 5 6 "github.com/fufuok/balancer" 7 ) 8 9 func main() { 10 // WeightedRoundRobin is the default balancer algorithm. 11 fmt.Println("default balancer name:", balancer.Name()) 12 13 // reinitialize the balancer items. 14 // D: will not select items with a weight of 0 15 wNodes := map[string]int{ 16 "A": 5, 17 "B": 3, 18 "C": 1, 19 "D": 0, 20 } 21 balancer.Update(wNodes) 22 23 // result of smooth selection is similar to: A A A B A B A B C 24 for i := 0; i < 9; i++ { 25 fmt.Print(balancer.Select(), " ") 26 } 27 fmt.Println() 28 29 // add an item to be selected 30 balancer.Add("E", 20) 31 // output: E 32 fmt.Println(balancer.Select()) 33 34 // get all items 35 wNodes = balancer.All().(map[string]int) 36 // map[A:5 B:3 C:1 D:0 E:20] 37 fmt.Printf("%+v\n", wNodes) 38 39 wNodes["E"] = 5 40 wNodes["D"] = 1 41 wNodes["A"] = 0 42 delete(wNodes, "B") 43 // reinitialize the balancer items 44 balancer.Update(wNodes) 45 46 // when the weight difference is large, it is not smooth: E E E E D E C E E E E D E C 47 for i := 0; i < 14; i++ { 48 fmt.Print(balancer.Select(), " ") 49 } 50 fmt.Println() 51 52 // reset the balancer items weight 53 balancer.Reset() 54 55 // remove an item 56 balancer.Remove("E") 57 58 // remove all items 59 balancer.RemoveAll() 60 }