generated from liuzhaomax/go-maxms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
consul.go
69 lines (65 loc) · 2.31 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
package core
import (
"fmt"
"github.com/hashicorp/consul/api"
"strconv"
)
type Consul struct {
Timeout int `mapstructure:"timeout"`
Interval int `mapstructure:"interval"`
DeregisterAfter int `mapstructure:"deregister_after"`
Endpoint
}
// ServiceRegister 服务注册
func (c *Consul) ServiceRegister() error {
defaultConfig := api.DefaultConfig()
defaultConfig.Address = fmt.Sprintf("%s:%s", cfg.Lib.Consul.Endpoint.Host, cfg.Lib.Consul.Endpoint.Port)
client, err := api.NewClient(defaultConfig)
if err != nil {
return err
}
agentServiceRegistration := new(api.AgentServiceRegistration)
agentServiceRegistration.Address = cfg.Server.Host
agentServiceRegistration.Name = cfg.App.Name
agentServiceRegistration.ID = ShortUUID()
intPort, _ := strconv.Atoi(cfg.Server.Port)
agentServiceRegistration.Port = intPort
agentServiceRegistration.Tags = []string{cfg.App.Name, cfg.Server.Protocol}
serverAddr := fmt.Sprintf("http://%s:%s/health", cfg.Server.Host, cfg.Server.Port)
check := api.AgentServiceCheck{
HTTP: serverAddr,
Timeout: fmt.Sprintf("%ds", cfg.Lib.Consul.Timeout),
Interval: fmt.Sprintf("%ds", cfg.Lib.Consul.Interval),
DeregisterCriticalServiceAfter: fmt.Sprintf("%ds", cfg.Lib.Consul.DeregisterAfter),
}
agentServiceRegistration.Check = &check
return client.Agent().ServiceRegister(agentServiceRegistration)
}
// ServiceDiscover 服务发现
func (c *Consul) ServiceDiscover() error {
if cfg.Downstreams == nil || len(cfg.Downstreams) == 0 {
return nil
}
defaultConfig := api.DefaultConfig()
defaultConfig.Address = fmt.Sprintf("%s:%s", cfg.Lib.Consul.Endpoint.Host, cfg.Lib.Consul.Endpoint.Port)
client, err := api.NewClient(defaultConfig)
if err != nil {
return err
}
for i, downstream := range cfg.Downstreams {
services, _, err := client.Catalog().Service(downstream.Name, EmptyString, nil)
if err != nil {
return err
}
if len(services) == 0 {
return fmt.Errorf("未发现可用服务: %s: %s:%s", downstream.Name, downstream.Host, downstream.Port)
}
for _, service := range services {
if downstream.Name == service.ServiceName {
cfg.Downstreams[i].Endpoint.Host = service.ServiceAddress
cfg.Downstreams[i].Endpoint.Port = strconv.Itoa(service.ServicePort)
}
}
}
return nil
}