/
client.go
110 lines (88 loc) · 1.86 KB
/
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
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
package rpcconn
import (
"io"
"net"
"net/rpc"
"sync"
)
type Client struct {
network string
dialer Address
mu *sync.RWMutex
c *rpc.Client
}
type Address interface {
String() string
}
func DialHTTP(network string, dialer Address) (*Client, error) {
client, err := rpc.DialHTTP(network, dialer.String())
if err != nil {
return nil, err
}
return &Client{
network: network,
dialer: dialer,
mu: new(sync.RWMutex),
c: client,
}, nil
}
func DialHTTPPath(network string, dialer Address, path string) (*Client, error) {
client, err := rpc.DialHTTPPath(network, dialer.String(), path)
if err != nil {
return nil, err
}
return &Client{
network: network,
dialer: dialer,
mu: new(sync.RWMutex),
c: client,
}, nil
}
func (client *Client) Close() error {
if client == nil {
return nil
}
client.mu.Lock()
defer client.mu.Unlock()
return client.c.Close()
}
func (client *Client) Call(method string, args, reply interface{}) error {
if client == nil {
return nil
}
client.mu.RLock()
err := client.c.Call(method, args, reply)
if err != nil && IsNetworkError(err) {
client.mu.RUnlock()
client.Reconnect()
//retry call
return client.Call(method, args, reply)
}
client.mu.RUnlock()
return err
}
func (client *Client) Reconnect() {
var rpcClient *rpc.Client
var err error
client.mu.Lock()
for {
rpcClient, err = rpc.DialHTTP(client.network, client.dialer.String())
if err == nil {
break
}
}
client.c = rpcClient
client.mu.Unlock()
}
func (client *Client) Go(method string, args, reply interface{}, done chan *rpc.Call) *rpc.Call {
if client == nil {
return nil
}
client.mu.RLock()
defer client.mu.RUnlock()
return client.c.Go(method, args, reply, done)
}
func IsNetworkError(err error) bool {
_, ok := err.(*net.OpError)
return ok || err == io.ErrUnexpectedEOF || err == rpc.ErrShutdown
}