-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjsonrpc.go
98 lines (81 loc) · 2.68 KB
/
jsonrpc.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
package letsgo
import (
"fmt"
"log"
"net/rpc"
"net/rpc/jsonrpc"
"sync"
)
//RPCconfig rpc服务器配置结构体
type RPCconfig struct {
Network string //网络 可以是tcp udp或者http
Address string //具体地址及端口
MicroserviceName string //rpc的微服务名称
}
//JSONRPCClient 结构体
type JSONRPCClient struct {
Service map[string]RPCconfig
Lock sync.Mutex
}
//NewJSONRPCClient 返回一个JSONRPCClient结构体指针
func NewJSONRPCClient() *JSONRPCClient {
return &JSONRPCClient{}
}
//Init JSONRPCClient初始化
func (c *JSONRPCClient) Init() {
c.Service = make(map[string]RPCconfig)
}
//Set 设置config
func (c *JSONRPCClient) Set(service, network, address, microservice_name string) error {
c.Lock.Lock()
c.Service[service] = RPCconfig{Network: network, Address: address, MicroserviceName: microservice_name}
c.Lock.Unlock()
return nil
}
//Dial 连接到一个rpc服务器
func (c *JSONRPCClient) Dial(service string) (*rpc.Client, error) {
thisservice, ok := c.Service[service]
if !ok {
return nil, fmt.Errorf("[error]jsonrpc Call unknown service: %s", service)
}
addr := "" //ip:port
if thisservice.Address != "" {
addr = thisservice.Address
} else if Default.MicroserviceClient != nil && Default.MicroserviceClient.IsActive() { //不填写传统地址才使用服务发现
var err error
addr, err = Default.MicroserviceClient.ServiceDiscovery(thisservice.MicroserviceName)
if err != nil {
return nil, fmt.Errorf("[error]jsonrpc ServiceDiscovery error: %s", err.Error())
}
log.Println("dial use microservice discovery, addr:", addr)
} else {
return nil, fmt.Errorf("[error]jsonrpc addr empty")
}
client, err := jsonrpc.Dial(thisservice.Network, addr)
if err != nil {
return nil, fmt.Errorf("[error]jsonrpc dial: %s", err.Error())
}
return client, nil
}
//DialWithMicroserviceFind 使用微服务发现并连接到rpc服务器
func (c *JSONRPCClient) DialWithServiceDiscovery(service string) (*rpc.Client, error) {
thisservice, ok := c.Service[service]
if !ok {
return nil, fmt.Errorf("[error]jsonrpc Call unknown service: %s", service)
}
if Default.MicroserviceClient == nil {
return nil, fmt.Errorf("[error]jsonrpc need init MicroserviceClient")
}
if !Default.MicroserviceClient.IsActive() {
return nil, fmt.Errorf("[error]jsonrpc need active MicroserviceClient")
}
addr, err := Default.MicroserviceClient.ServiceDiscovery(thisservice.MicroserviceName)
if err != nil {
return nil, fmt.Errorf("[error]jsonrpc ServiceDiscovery error:", err.Error())
}
client, err := jsonrpc.Dial(thisservice.Network, addr)
if err != nil {
return nil, fmt.Errorf("[error]jsonrpc dial: %s", err.Error())
}
return client, nil
}