From 8f73a779a8749beeeb812e872ace07756ef7453b Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Tue, 26 Sep 2017 19:58:43 +0800 Subject: [PATCH] add some comments and refactor --- engine_group_policy.go | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/engine_group_policy.go b/engine_group_policy.go index 175f8e39..5ac89f71 100644 --- a/engine_group_policy.go +++ b/engine_group_policy.go @@ -10,24 +10,32 @@ import ( "time" ) +// GroupPolicy is be used by chosing the current slave from slaves type GroupPolicy interface { Slave(*EngineGroup) *Engine } +// GroupPolicyHandler should be used when a function is a GroupPolicy +type GroupPolicyHandler func(*EngineGroup) *Engine + +// RandomPolicy implmentes randomly chose the slave of slaves type RandomPolicy struct { r *rand.Rand } +// NewRandomPolicy creates a RandomPolicy func NewRandomPolicy() *RandomPolicy { return &RandomPolicy{ r: rand.New(rand.NewSource(time.Now().UnixNano())), } } +// Slave randomly choses the slave of slaves func (policy *RandomPolicy) Slave(g *EngineGroup) *Engine { return g.Slaves()[policy.r.Intn(len(g.Slaves()))] } +// WeightRandomPolicy implmentes randomly chose the slave of slaves type WeightRandomPolicy struct { weights []int rands []int @@ -123,14 +131,8 @@ func (policy *WeightRoundRobinPolicy) Slave(g *EngineGroup) *Engine { return slaves[idx] } -type LeastConnPolicy struct { -} - -func NewLeastConnPolicy() *LeastConnPolicy { - return &LeastConnPolicy{} -} - -func (policy *LeastConnPolicy) Slave(g *EngineGroup) *Engine { +// LeastConnPolicy implements GroupPolicy, every time will get the least connections slave +var LeastConnPolicy GroupPolicyHandler = func(g *EngineGroup) *Engine { var slaves = g.Slaves() connections := 0 idx := 0