forked from smallnest/rpcx
/
oneclient_pool.go
87 lines (75 loc) ยท 2.45 KB
/
oneclient_pool.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
package client
import (
"sync/atomic"
"github.com/fitlivingmm/rpcx/protocol"
)
// OneClientPool is a oneclient pool with fixed size.
// It uses roundrobin algorithm to call its xclients.
// All oneclients share the same configurations such as ServiceDiscovery and serverMessageChan.
type OneClientPool struct {
count uint64
index uint64
oneclients []*OneClient
auth string
failMode FailMode
selectMode SelectMode
discovery ServiceDiscovery
option Option
serverMessageChan chan<- *protocol.Message
}
// NewOneClientPool creates a fixed size OneClient pool.
func NewOneClientPool(count int, failMode FailMode, selectMode SelectMode, discovery ServiceDiscovery, option Option) *OneClientPool {
pool := &OneClientPool{
count: uint64(count),
oneclients: make([]*OneClient, count),
failMode: failMode,
selectMode: selectMode,
discovery: discovery,
option: option,
}
for i := 0; i < count; i++ {
oneclient := NewOneClient(failMode, selectMode, discovery, option)
pool.oneclients[i] = oneclient
}
return pool
}
// NewBidirectionalOneClientPool creates a BidirectionalOneClient pool with fixed size.
func NewBidirectionalOneClientPool(count int, failMode FailMode, selectMode SelectMode, discovery ServiceDiscovery, option Option, serverMessageChan chan<- *protocol.Message) *OneClientPool {
pool := &OneClientPool{
count: uint64(count),
oneclients: make([]*OneClient, count),
failMode: failMode,
selectMode: selectMode,
discovery: discovery,
option: option,
serverMessageChan: serverMessageChan,
}
for i := 0; i < count; i++ {
oneclient := NewBidirectionalOneClient(failMode, selectMode, discovery, option, serverMessageChan)
pool.oneclients[i] = oneclient
}
return pool
}
// Auth sets s token for Authentication.
func (c *OneClientPool) Auth(auth string) {
c.auth = auth
for _, v := range c.oneclients {
v.Auth(auth)
}
}
// Get returns a OneClient.
// It does not remove this OneClient from its cache so you don't need to put it back.
// Don't close this OneClient because maybe other goroutines are using this OneClient.
func (p *OneClientPool) Get() *OneClient {
i := atomic.AddUint64(&p.index, 1)
picked := int(i % p.count)
return p.oneclients[picked]
}
// Close this pool.
// Please make sure it won't be used any more.
func (p OneClientPool) Close() {
for _, c := range p.oneclients {
c.Close()
}
p.oneclients = nil
}