github.com/fufuok/balancer@v1.0.0/examples/wrr/main.go (about)

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