-
Notifications
You must be signed in to change notification settings - Fork 0
/
register.go
executable file
·97 lines (83 loc) · 1.97 KB
/
register.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
package nacos
import (
"fmt"
"log"
"net"
"os"
"strconv"
"strings"
"github.com/nacos-group/nacos-sdk-go/v2/clients"
"github.com/nacos-group/nacos-sdk-go/v2/vo"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/core/proc"
"github.com/zeromicro/go-zero/core/netx"
)
// RegisterService register service to nacos
func RegisterService(opts *Options) error {
pubListenOn := figureOutListenOn(opts.ListenOn)
host, ports, err := net.SplitHostPort(pubListenOn)
if err != nil {
return fmt.Errorf("failed parsing address error: %v", err)
}
port, _ := strconv.ParseUint(ports, 10, 16)
client, err := clients.NewNamingClient(
vo.NacosClientParam{
ServerConfigs: opts.ServerConfig,
ClientConfig: opts.ClientConfig,
},
)
if err != nil {
log.Panic(err)
}
// service register
_, err = client.RegisterInstance(vo.RegisterInstanceParam{
ServiceName: opts.ServiceName,
Ip: host,
Port: port,
Weight: opts.Weight,
Enable: true,
Healthy: true,
Ephemeral: true,
Metadata: opts.Metadata,
ClusterName: opts.Cluster,
GroupName: opts.Group,
})
if err != nil {
return err
}
// service deregister
proc.AddShutdownListener(func() {
_, err := client.DeregisterInstance(vo.DeregisterInstanceParam{
Ip: host,
Port: port,
ServiceName: opts.ServiceName,
Cluster: opts.Cluster,
GroupName: opts.Group,
Ephemeral: true,
})
if err != nil {
logx.Info("deregister service error: ", err.Error())
} else {
logx.Info("deregistered service from nacos server.")
}
})
return nil
}
func figureOutListenOn(listenOn string) string {
fields := strings.Split(listenOn, ":")
if len(fields) == 0 {
return listenOn
}
host := fields[0]
if len(host) > 0 && host != allEths {
return listenOn
}
ip := os.Getenv(envPodIP)
if len(ip) == 0 {
ip = netx.InternalIp()
}
if len(ip) == 0 {
return listenOn
}
return strings.Join(append([]string{ip}, fields[1:]...), ":")
}