github.com/fufuok/balancer@v1.0.0/examples/hash/main.go (about) 1 package main 2 3 import ( 4 "fmt" 5 6 "github.com/fufuok/balancer" 7 ) 8 9 func main() { 10 nodes := []string{"A", "B", "C"} 11 // lb := balancer.New(balancer.ConsistentHash, nodes) 12 lb := balancer.NewConsistentHash(nodes) 13 fmt.Println("balancer name:", lb.Name()) 14 15 // B B B B B 16 for i := 0; i < 5; i++ { 17 fmt.Print(lb.Select(), " ") 18 } 19 fmt.Println() 20 21 // add an item to be selected 22 lb.Add("E") 23 // output: B 24 fmt.Println(lb.Select()) 25 // output: B 26 fmt.Println(lb.Select()) 27 // output: C 28 fmt.Println(lb.Select("1.2.3.4")) 29 30 // get all items 31 nodes = lb.All().([]string) 32 // [A B C E] 33 fmt.Printf("%+v\n", nodes) 34 35 nodes = append(nodes, "F") 36 // reinitialize the balancer items 37 lb.Update(nodes) 38 39 // B B B B B B B 40 for i := 0; i < 7; i++ { 41 fmt.Print(lb.Select(), " ") 42 } 43 fmt.Println() 44 45 // output: F 46 fmt.Println(lb.Select("1.2.3.4")) 47 48 lb.Remove("F") 49 50 // output: A 51 fmt.Println(lb.Select("1.2.3.4")) 52 53 // remove all items 54 lb.RemoveAll() 55 }