Skip to content

Commit f663326

Browse files
committed
增加loadbalance
1 parent 8db160b commit f663326

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

lb/loadbalance.go

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
// Copyright (C) 2019-2020, Xiongfa Li.
2+
// @author xiongfa.li
3+
// @version V1.0
4+
// Description:
5+
6+
package lb
7+
8+
import (
9+
"math/rand"
10+
)
11+
12+
type LoadBalance interface {
13+
Select() interface{}
14+
}
15+
16+
type BaseLoadBalance struct {
17+
invokers []interface{}
18+
}
19+
20+
func (lb *BaseLoadBalance) AddFactory(invokers ...interface{}) {
21+
lb.invokers = append(lb.invokers, invokers...)
22+
}
23+
24+
type RandomLoadBalance struct {
25+
BaseLoadBalance
26+
rand rand.Rand
27+
}
28+
29+
func (lb *RandomLoadBalance) Select() interface{} {
30+
size := len(lb.invokers)
31+
if size == 0 {
32+
return nil
33+
}
34+
35+
return lb.invokers[lb.rand.Intn(size-1)]
36+
}
37+
38+
type RoundRobbinLoadBalance struct {
39+
BaseLoadBalance
40+
i int
41+
}
42+
43+
func (lb *RoundRobbinLoadBalance) Select() interface{} {
44+
size := len(lb.invokers)
45+
if size == 0 {
46+
return nil
47+
}
48+
49+
fac := lb.invokers[lb.i]
50+
lb.i = (lb.i + 1) % size
51+
return fac
52+
}

0 commit comments

Comments
 (0)