forked from zehuamama/balancer
/
random.go
67 lines (57 loc) 路 1.28 KB
/
random.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
// Copyright 2022 <mzh.scnu@qq.com>. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package balancer
import (
"math/rand"
"sync"
"time"
)
func init() {
factories[RandomBalancer] = NewRandom
}
// Random will randomly select a http server from the server
type Random struct {
sync.RWMutex
hosts []string
rnd *rand.Rand
}
// NewRandom create new Random balancer
func NewRandom(hosts []string) Balancer {
return &Random{hosts: hosts,
rnd: rand.New(rand.NewSource(time.Now().UnixNano()))}
}
// Add new host to the balancer
func (r *Random) Add(host string) {
r.Lock()
defer r.Unlock()
for _, h := range r.hosts {
if h == host {
return
}
}
r.hosts = append(r.hosts, host)
}
// Remove new host from the balancer
func (r *Random) Remove(host string) {
r.Lock()
defer r.Unlock()
for i, h := range r.hosts {
if h == host {
r.hosts = append(r.hosts[:i], r.hosts[i+1:]...)
}
}
}
// Balance selects a suitable host according
func (r *Random) Balance(_ string) (string, error) {
r.RLock()
defer r.RUnlock()
if len(r.hosts) == 0 {
return "", NoHostError
}
return r.hosts[r.rnd.Intn(len(r.hosts))], nil
}
// Inc .
func (r *Random) Inc(_ string) {}
// Done .
func (r *Random) Done(_ string) {}