Files
FastDeploy/fastdeploy/golang_router/internal/scheduler/handler/power_of_two.go
T
mouxin 0a92e96f20 [Feature] Add Golang-based Router for Request Scheduling and Load Balancing (#5882)
* [Feature] add golang router

* [Feature] add golang router

* [Feature] add golang router

* [Feature] add golang router

* [Feature] add golang router

* [Feature] Add Golang-based Router for Request Scheduling and Load Balancing

* [Feature] Add Golang-based Router for Request Scheduling and Load Balancing

* [Feature] Add Golang-based Router for Request Scheduling and Load Balancing

* [Feature] Add Golang-based Router for Request Scheduling and Load Balancing

---------

Co-authored-by: mouxin <mouxin@baidu.com>
2026-01-07 21:28:08 +08:00

40 lines
752 B
Go

package handler
import (
"context"
"math/rand"
)
func PowerOfTwoSelectWorker(ctx context.Context, workers []string, message string) (string, error) {
if len(workers) == 0 {
return "", nil
}
if len(workers) == 1 {
return workers[0], nil
}
length := len(workers)
randomNum1 := rand.Intn(length)
randomNum2 := rand.Intn(length)
for randomNum2 == randomNum1 {
randomNum2 = rand.Intn(length)
}
worker1 := workers[randomNum1]
worker2 := workers[randomNum2]
counter1 := GetOrCreateCounter(ctx, worker1)
counter2 := GetOrCreateCounter(ctx, worker2)
load1 := counter1.Get()
load2 := counter2.Get()
var selectedURL string
if load1 <= load2 {
selectedURL = worker1
} else {
selectedURL = worker2
}
return selectedURL, nil
}