forked from sjclijie/go-zero
/
publisher.go
100 lines (83 loc) · 2.2 KB
/
publisher.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 consul
import (
"fmt"
"github.com/hashicorp/consul/api"
"github.com/sjclijie/go-zero/core/lang"
"github.com/sjclijie/go-zero/core/proc"
"github.com/sjclijie/go-zero/core/syncx"
"net"
"strconv"
"time"
)
type (
PublisherOption func(client *Publisher)
Publisher struct {
client *api.Client
config ConsulConf
listenHost string
listenPort int
serviceId string
quit *syncx.DoneChan
pauseChan chan lang.PlaceholderType
resumeChan chan lang.PlaceholderType
}
)
func NewPublisher(config ConsulConf, listenOn string, opts ...PublisherOption) (*Publisher, error) {
host, portStr, err := net.SplitHostPort(listenOn)
if err != nil {
return nil, err
}
port, err := strconv.Atoi(portStr)
if err != nil {
return nil, err
}
publisher := &Publisher{
config: config,
serviceId: fmt.Sprintf("%v-%v:%v", config.Key, host, port),
listenHost: host,
listenPort: port,
quit: syncx.NewDoneChan(),
pauseChan: make(chan lang.PlaceholderType),
resumeChan: make(chan lang.PlaceholderType),
}
for _, opt := range opts {
opt(publisher)
}
c := api.DefaultConfig()
c.Address = config.Host
c.Token = config.Token
if client, err := api.NewClient(c); err != nil {
return nil, err
} else {
publisher.client = client
}
return publisher, nil
}
func (p *Publisher) Register() error {
registration := &api.AgentServiceRegistration{
ID: p.serviceId,
Name: p.config.Key,
Tags: []string{p.config.Key},
Address: p.listenHost,
Port: p.listenPort,
}
if p.config.HealthCheck {
registration.Check = &api.AgentServiceCheck{
Interval: time.Duration(5 * time.Second).String(),
Timeout: time.Duration(5 * time.Second).String(),
Args: []string{"ls"},
GRPC: fmt.Sprintf("%v/%v", p.config.Host, p.config.Key),
DeregisterCriticalServiceAfter: time.Duration(30 * time.Second).String(),
}
}
if err := p.client.Agent().ServiceRegister(registration); err != nil {
return err
}
proc.AddWrapUpListener(func() {
p.Deregister()
})
return nil
}
func (p *Publisher) Deregister() error {
return p.client.Agent().ServiceDeregister(p.serviceId)
}