-
Notifications
You must be signed in to change notification settings - Fork 0
/
consul.go
100 lines (93 loc) · 2.48 KB
/
consul.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
package registry
import (
consul "github.com/hashicorp/consul/api"
"github.com/justcy/ygo/ygo/registry/iface"
"github.com/justcy/ygo/ygo/utils"
"github.com/justcy/ygo/ygo/ylog"
"sync"
)
type ConsulRegistry struct {
sync.Mutex
client *consul.Client
config *consul.Config
QueryOptions *consul.QueryOptions
}
func (c *ConsulRegistry) Init() {
ylog.Debug("consul Registry init")
if c.config == nil {
ylog.Debug(utils.GlobalObject.ConsulAddress)
c.config = &consul.Config{
Address: utils.GlobalObject.ConsulAddress,
}
ylog.Infof("%v,$v",c.config,c.client)
}
if c.client == nil {
var err error
c.client, err = consul.NewClient(c.config)
if err != nil {
ylog.Info(err)
}
}
}
func (c *ConsulRegistry) Register(service iface.Service) {
c.Init()
tags := encodeMetadata(service.Metadata)
tags = append(tags, encodeVersion(service.Version)...)
registration := consul.AgentServiceRegistration{
ID: service.Id,
Name: service.Name,
Port: service.Port,
Tags: tags,
Address: service.Address,
Check: &consul.AgentServiceCheck{
TCP: service.Address,
Timeout: "5s",
Interval: "5s",
DeregisterCriticalServiceAfter: "600s",
},
}
ylog.Infof("%v,$v",c.config,c.client)
if err := c.client.Agent().ServiceRegister(®istration); err != nil {
ylog.Error(err)
}
}
func (c *ConsulRegistry) UnRegister(service iface.Service) {
c.Init()
c.client.Agent().ServiceDeregister(service.Id)
}
func (c *ConsulRegistry) UnRegisterById(id string) {
c.Init()
c.client.Agent().ServiceDeregister(id)
}
func (c *ConsulRegistry) GetService(name string,opt ...GetOptions) ([]*iface.Service, error){
c.Init()
var resp []*consul.ServiceEntry
var err error
resp ,_,err = c.client.Health().Service(name,"",false,c.QueryOptions)
if err != nil {
return nil, err
}
var services []*iface.Service
for _, s := range resp {
ylog.Debugf("%s,%s,%s:%d",s.Checks[0].Status,s.Service.Service,s.Service.Address,s.Service.Port)
if s.Service.Service != name {
continue
}
// address is service address
address := s.Service.Address
version, _ := decodeVersion(s.Service.Tags)
// use node address
if len(address) == 0 {
address = s.Node.Address
}
service := &iface.Service{
Metadata: decodeMetadata(s.Service.Tags),
Name: s.Service.Service,
Version: version,
Address: s.Service.Address,
Port: s.Service.Port,
}
services = append(services, service)
}
return services,nil
}