forked from viphxin/xingo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
child.go
114 lines (95 loc) · 2.17 KB
/
child.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
package cluster
import (
"errors"
"fmt"
"github.com/viphxin/xingo/iface"
"github.com/viphxin/xingo/logger"
"math/rand"
"strings"
"sync"
)
type Child struct {
name string
rpc *XingoRpc
}
func NewChild(name string, conn iface.IWriter) *Child {
return &Child{
name: name,
rpc: NewXingoRpc(conn),
}
}
func (this *Child) GetName() string {
return this.name
}
func (this *Child) CallChildNotForResult(target string, args ...interface{}) error {
return this.rpc.CallRpcNotForResult(target, args...)
}
func (this *Child) CallChildForResult(target string, args ...interface{}) (*RpcData, error) {
return this.rpc.CallRpcForResult(target, args...)
}
type ChildMgr struct {
childs map[string]*Child
sync.RWMutex
}
func NewChildMgr() *ChildMgr {
return &ChildMgr{
childs: make(map[string]*Child, 0),
}
}
func (this *ChildMgr) AddChild(name string, conn iface.IWriter) {
this.Lock()
defer this.Unlock()
this.childs[name] = NewChild(name, conn)
logger.Debug(fmt.Sprintf("child %s connected.", name))
}
func (this *ChildMgr) RemoveChild(name string) {
this.Lock()
defer this.Unlock()
delete(this.childs, name)
logger.Debug(fmt.Sprintf("child %s lostconnection.", name))
}
func (this *ChildMgr) GetChild(name string) (*Child, error) {
this.RLock()
defer this.RUnlock()
child, ok := this.childs[name]
if ok {
return child, nil
} else {
return nil, errors.New(fmt.Sprintf("no child named %s", name))
}
}
func (this *ChildMgr) GetChildsByPrefix(namePrefix string) []*Child {
this.RLock()
defer this.RUnlock()
childs := make([]*Child, 0)
for k, v := range this.childs {
if strings.HasPrefix(k, namePrefix) {
childs = append(childs, v)
}
}
return childs
}
func (this *ChildMgr) GetChilds() []*Child {
this.RLock()
defer this.RUnlock()
childs := make([]*Child, 0)
for _, v := range this.childs {
childs = append(childs, v)
}
return childs
}
func (this *ChildMgr) GetRandomChild(namesuffix string) *Child {
childs := make([]*Child, 0)
if namesuffix != "" {
//一类
childs = this.GetChildsByPrefix(namesuffix)
} else {
//所有
childs = this.GetChilds()
}
if len(childs) > 0 {
pos := rand.Intn(len(childs))
return childs[pos]
}
return nil
}