forked from open-falcon/falcon-plus
/
rpc.go
71 lines (55 loc) · 1.05 KB
/
rpc.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
package g
import (
"github.com/toolkits/net"
"log"
"math"
"net/rpc"
"sync"
"time"
)
type SingleConnRpcClient struct {
sync.Mutex
rpcClient *rpc.Client
RpcServers []string
Timeout time.Duration
}
func (this *SingleConnRpcClient) close() {
if this.rpcClient != nil {
this.rpcClient.Close()
this.rpcClient = nil
}
}
func (this *SingleConnRpcClient) insureConn() {
if this.rpcClient != nil {
return
}
var err error
var retry int = 1
for {
if this.rpcClient != nil {
return
}
for _, s := range this.RpcServers {
this.rpcClient, err = net.JsonRpcClient("tcp", s, this.Timeout)
if err == nil {
return
}
log.Printf("dial %s fail: %s", s, err)
}
if retry > 6 {
retry = 1
}
time.Sleep(time.Duration(math.Pow(2.0, float64(retry))) * time.Second)
retry++
}
}
func (this *SingleConnRpcClient) Call(method string, args interface{}, reply interface{}) error {
this.Lock()
defer this.Unlock()
this.insureConn()
err := this.rpcClient.Call(method, args, reply)
if err != nil {
this.close()
}
return err
}