github.com/fufuok/balancer@v1.0.0/balancer.go (about) 1 package balancer 2 3 type Balancer interface { 4 // Add add an item to be selected. 5 // weight is only used for WeightedRoundRobin/SmoothWeightedRoundRobin/WeightedRand, default: 1 6 Add(item string, weight ...int) 7 8 // All get all items. 9 // RoundRobin/Random/ConsistentHash: []string 10 // WeightedRoundRobin/SmoothWeightedRoundRobin/WeightedRand: map[string]int 11 All() interface{} 12 13 // Select gets next selected item. 14 // key is only used for ConsistentHash 15 Select(key ...string) string 16 17 // Name load balancer name. 18 Name() string 19 20 // Remove remove an item. 21 // asClean: clean up or remove only one 22 Remove(item string, asClean ...bool) bool 23 24 // RemoveAll remove all items. 25 RemoveAll() 26 27 // Reset reset the balancer. 28 Reset() 29 30 // Update reinitialize the balancer items. 31 // RoundRobin/Random/ConsistentHash: []string 32 // WeightedRoundRobin/SmoothWeightedRoundRobin/WeightedRand: map[string]int 33 Update(items interface{}) bool 34 } 35 36 // Mode defines the selectable balancer algorithm. 37 type Mode int 38 39 const ( 40 // WeightedRoundRobin is the default balancer algorithm. 41 WeightedRoundRobin Mode = iota 42 SmoothWeightedRoundRobin 43 WeightedRand 44 ConsistentHash 45 RoundRobin 46 Random 47 ) 48 49 func (m Mode) String() string { 50 switch m { 51 case WeightedRoundRobin: 52 return "WeightedRoundRobin" 53 case SmoothWeightedRoundRobin: 54 return "SmoothWeightedRoundRobin" 55 case WeightedRand: 56 return "WeightedRand" 57 case ConsistentHash: 58 return "ConsistentHash" 59 case RoundRobin: 60 return "RoundRobin" 61 case Random: 62 return "Random" 63 default: 64 return "" 65 } 66 } 67 68 // New create a balancer with or without items. 69 // RoundRobin/Random/ConsistentHash: []string 70 // WeightedRoundRobin/SmoothWeightedRoundRobin/WeightedRand: map[string]int 71 func New(b Mode, itemsMap map[string]int, itemsList []string) Balancer { 72 switch b { 73 case SmoothWeightedRoundRobin: 74 return NewSmoothWeightedRoundRobin(itemsMap) 75 case WeightedRand: 76 return NewWeightedRand(itemsMap) 77 case ConsistentHash: 78 return NewConsistentHash(itemsList) 79 case RoundRobin: 80 return NewRoundRobin(itemsList) 81 case Random: 82 return NewRandom(itemsList) 83 default: 84 return NewWeightedRoundRobin(itemsMap) 85 } 86 }