Implement pN load balancing strategy (#1188)

This commit is contained in:
Timofey 2020-03-20 16:55:03 +00:00 committed by GitHub
parent a1f3b34390
commit 014a75c0ec
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 17 additions and 16 deletions

View File

@ -363,17 +363,22 @@ func ConfigLoad(proxy *Proxy, flags *ConfigFlags) error {
switch strings.ToLower(config.LBStrategy) {
case "":
// default
case "p2":
lbStrategy = LBStrategyP2
case "ph":
lbStrategy = LBStrategyPH
case "fastest":
case "first":
lbStrategy = LBStrategyFirst
lbStrategy = LBStrategy(1)
case "random":
lbStrategy = LBStrategyRandom
default:
dlog.Warnf("Unknown load balancing strategy: [%s]", config.LBStrategy)
n, err := strconv.ParseUint(strings.TrimPrefix(config.LBStrategy, "p"), 10, 64)
if err == nil && n >= 1 {
lbStrategy = LBStrategy(n)
} else {
dlog.Warnf("Unknown load balancing strategy: [%s]", config.LBStrategy)
}
}
proxy.serversInfo.lbStrategy = lbStrategy
proxy.serversInfo.lbEstimator = config.LBEstimator

View File

@ -126,6 +126,7 @@ keepalive = 30
## Load-balancing strategy: 'p2' (default), 'ph', 'first' or 'random'
## Use pN where N is a positive number to choose between N first fastest servers.
# lb_strategy = 'p2'

View File

@ -65,14 +65,11 @@ type ServerInfo struct {
type LBStrategy int
const (
LBStrategyNone = LBStrategy(iota)
LBStrategyP2
LBStrategyPH
LBStrategyFirst
LBStrategyRandom
LBStrategyRandom = LBStrategy(0)
LBStrategyPH = LBStrategy(-1)
)
const DefaultLBStrategy = LBStrategyP2
const DefaultLBStrategy = LBStrategy(2)
type ServersInfo struct {
sync.RWMutex
@ -211,14 +208,12 @@ func (serversInfo *ServersInfo) getOne() *ServerInfo {
}
var candidate int
switch serversInfo.lbStrategy {
case LBStrategyFirst:
candidate = 0
case LBStrategyPH:
case -1: // First half
candidate = rand.Intn(Max(Min(serversCount, 2), serversCount/2))
case LBStrategyRandom:
case 0: // Random
candidate = rand.Intn(serversCount)
default:
candidate = rand.Intn(Min(serversCount, 2))
default: // First N
candidate = rand.Intn(int(serversInfo.lbStrategy)) % serversCount
}
serverInfo := serversInfo.inner[candidate]
dlog.Debugf("Using candidate [%s] RTT: %d", (*serverInfo).Name, int((*serverInfo).rtt.Value()))