-
Notifications
You must be signed in to change notification settings - Fork 52
/
abstract.go
86 lines (72 loc) · 1.9 KB
/
abstract.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
76
77
78
79
80
81
82
83
84
85
86
package dispatcher
import (
"github.com/dobyte/due/v2/core/endpoint"
"github.com/dobyte/due/v2/errors"
"sync/atomic"
)
type serviceEndpoint struct {
insID string
endpoint *endpoint.Endpoint
}
type abstract struct {
counter int64
dispatcher *Dispatcher
endpointMap map[string]*serviceEndpoint
endpointArr []*serviceEndpoint
}
// FindEndpoint 查询路由服务端点
func (a *abstract) FindEndpoint(insID ...string) (*endpoint.Endpoint, error) {
if len(insID) == 0 || insID[0] == "" {
switch a.dispatcher.strategy {
case Random:
return a.randomDispatch()
case RoundRobin:
return a.roundRobinDispatch()
default:
return a.randomDispatch()
}
}
return a.directDispatch(insID[0])
}
// IterateEndpoint 迭代服务端口
func (a *abstract) IterateEndpoint(fn func(insID string, ep *endpoint.Endpoint) bool) {
for _, se := range a.endpointArr {
if fn(se.insID, se.endpoint) == false {
break
}
}
}
// 添加服务端点
func (a *abstract) addEndpoint(insID string, ep *endpoint.Endpoint) {
if sep, ok := a.endpointMap[insID]; ok {
sep.endpoint = ep
} else {
sep = &serviceEndpoint{insID: insID, endpoint: ep}
a.endpointArr = append(a.endpointArr, sep)
a.endpointMap[insID] = sep
}
}
// 直接分配
func (a *abstract) directDispatch(insID string) (*endpoint.Endpoint, error) {
sep, ok := a.endpointMap[insID]
if !ok {
return nil, errors.ErrNotFoundEndpoint
}
return sep.endpoint, nil
}
// 随机分配
func (a *abstract) randomDispatch() (*endpoint.Endpoint, error) {
for _, sep := range a.endpointMap {
return sep.endpoint, nil
}
return nil, errors.ErrNotFoundEndpoint
}
// 轮询分配
func (a *abstract) roundRobinDispatch() (*endpoint.Endpoint, error) {
if len(a.endpointArr) == 0 {
return nil, errors.ErrNotFoundEndpoint
}
counter := atomic.AddInt64(&a.counter, 1)
index := int(counter % int64(len(a.endpointArr)))
return a.endpointArr[index].endpoint, nil
}