-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy patheasy_client.go
66 lines (53 loc) · 2.07 KB
/
easy_client.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
package easycall
import (
"sync"
"time"
)
type EasyClient struct {
clients map[string]*ServiceClient
mutex *sync.Mutex
endpoints []string
poolSize int
loadbalanceType int
}
func NewEasyClient(endpoints []string, poolSize int, loadbalanceType int) *EasyClient {
return &EasyClient{endpoints: endpoints, mutex: &sync.Mutex{}, clients: make(map[string]*ServiceClient, 0), poolSize: poolSize, loadbalanceType: loadbalanceType}
}
func (ec *EasyClient) Request(serviceName string, method string, reqBody interface{}, respBody interface{}, timeout time.Duration) error {
ch, err := ec.RequestAsyncWithHead(FORMAT_MSGPACK, NewEasyHead().SetService(serviceName).SetMethod(method), reqBody, timeout)
if err != nil {
return err
}
respPkg := <-ch
if respPkg == nil {
return NewSystemError(ERROR_TIME_OUT, "request time out")
}
if respPkg.GetHead().GetRet() != 0 {
return NewLogicError(respPkg.GetHead().GetRet(), respPkg.GetHead().GetMsg())
}
return respPkg.DecodeBody(respBody)
}
func (ec *EasyClient) RequestAsync(serviceName string, method string, reqBody interface{}, timeout time.Duration) (chan *EasyPackage, error) {
return ec.RequestAsyncWithHead(FORMAT_MSGPACK, NewEasyHead().SetService(serviceName).SetMethod(method), reqBody, timeout)
}
func (ec *EasyClient) RequestWithHead(format byte, head *EasyHead, reqBody interface{}, timeout time.Duration) (*EasyPackage, error) {
ch, err := ec.RequestAsyncWithHead(format, head, reqBody, timeout)
if err != nil {
return nil, err
}
respPkg := <-ch
if respPkg == nil {
return nil, NewSystemError(ERROR_TIME_OUT, "request time out")
}
return respPkg, nil
}
func (ec *EasyClient) RequestAsyncWithHead(format byte, head *EasyHead, reqBody interface{}, timeout time.Duration) (chan *EasyPackage, error) {
ec.mutex.Lock()
client := ec.clients[head.GetService()]
if client == nil {
client = NewServiceClient(ec.endpoints, head.GetService(), ec.poolSize, ec.loadbalanceType)
ec.clients[head.GetService()] = client
}
ec.mutex.Unlock()
return client.RequestAsyncWithHead(format, head, reqBody, timeout)
}