-
-
Notifications
You must be signed in to change notification settings - Fork 15
/
loadbalancer.go
75 lines (64 loc) · 1.71 KB
/
loadbalancer.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package dbresolver
import (
"database/sql"
"math/rand"
"sync/atomic"
"time"
)
// DBConnection is the generic type for DB and Stmt operation
type DBConnection interface {
*sql.DB | *sql.Stmt
}
// LoadBalancer define the load balancer contract
type LoadBalancer[T DBConnection] interface {
Resolve([]T) T
Name() LoadBalancerPolicy
predict(n int) int
}
// RandomLoadBalancer represent for Random LB policy
type RandomLoadBalancer[T DBConnection] struct {
randInt chan int
}
// RandomLoadBalancer return the LB policy name
func (lb RandomLoadBalancer[T]) Name() LoadBalancerPolicy {
return RandomLB
}
// Resolve return the resolved option for Random LB.
// Marked with go:nosplit to prevent preemption.
//
//go:nosplit
func (lb RandomLoadBalancer[T]) Resolve(dbs []T) T {
if len(lb.randInt) == 0 {
lb.predict(len(dbs))
}
randomInt := <-lb.randInt
return dbs[randomInt]
}
func (lb RandomLoadBalancer[T]) predict(n int) int {
r := rand.New(rand.NewSource(time.Now().UnixNano()))
max := n - 1 //nolint
min := 0 //nolint
idx := r.Intn(max-min+1) + min
lb.randInt <- idx
return idx
}
// RoundRobinLoadBalancer represent for RoundRobin LB policy
type RoundRobinLoadBalancer[T DBConnection] struct {
counter uint64 // Monotonically incrementing counter on every call
}
// Name return the LB policy name
func (lb RoundRobinLoadBalancer[T]) Name() LoadBalancerPolicy {
return RoundRobinLB
}
// Resolve return the resolved option for RoundRobin LB
func (lb *RoundRobinLoadBalancer[T]) Resolve(dbs []T) T {
idx := lb.predict(len(dbs))
return dbs[idx]
}
func (lb *RoundRobinLoadBalancer[T]) predict(n int) int {
if n <= 1 {
return 0
}
// counter := lb.counter
return int(atomic.AddUint64(&lb.counter, 1) % uint64(n))
}