-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstrategy.go
More file actions
50 lines (44 loc) · 1.23 KB
/
strategy.go
File metadata and controls
50 lines (44 loc) · 1.23 KB
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
package main
import (
"fmt"
"math/rand"
"time"
)
type LoadBalancer interface {
SelectServer() (*server, error)
}
type RoundRobinLoadBalancer struct{}
type RandomLoadBalancer struct{}
type LeastConnectionsLoadBalancer struct{} // Placeholder
func (r *RoundRobinLoadBalancer) SelectServer() (*server, error) {
mutex.Lock()
defer mutex.Unlock()
for i := 0; i < len(serverList); i++ {
nextIndex := (lastServedIndex + 1) % len(serverList)
server := serverList[nextIndex]
lastServedIndex = nextIndex
if server.Health {
return server, nil
}
}
return nil, fmt.Errorf("no healthy server found in round robin")
}
func (r *RandomLoadBalancer) SelectServer() (*server, error) {
rand.Seed(time.Now().UnixNano())
mutex.Lock()
defer mutex.Unlock()
healthyServers := []*server{}
for _, server := range serverList {
if server.Health {
healthyServers = append(healthyServers, server)
}
}
if len(healthyServers) == 0 {
return nil, fmt.Errorf("no healthy server found in random selection")
}
return healthyServers[rand.Intn(len(healthyServers))], nil
}
func (l *LeastConnectionsLoadBalancer) SelectServer() (*server, error) {
// Placeholder for real implementation
return nil, fmt.Errorf("least connections strategy not implemented")
}