forked from whatvn/denny
-
Notifications
You must be signed in to change notification settings - Fork 0
/
naming.go
76 lines (66 loc) · 1.81 KB
/
naming.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
package etcd
import (
"context"
"github.com/kenkinsai/denny/naming"
"go.etcd.io/etcd/clientv3"
"time"
)
// Register starts etcd client and check for registered key, if it's not available
// in etcd storage, it will write service host:port to etcd and start watching to keep writing
// if its data is not available again
func (r *etcd) Register(addr string, ttl int) error {
var (
ticker = time.NewTicker(time.Second * time.Duration(ttl))
err error
svcPath = "/" + naming.Prefix + "/" + r.serviceName + "/" + addr
)
r.Infof("register %s with registy", svcPath)
err = r.register(addr, ttl)
if err != nil {
r.Errorf("error %v", err)
}
go func() {
for {
select {
case _ = <-ticker.C:
resp, err := r.cli.Get(context.Background(), svcPath)
if err != nil {
r.Errorf("error %v", err)
} else if resp.Count == 0 {
err = r.register(addr, ttl)
if err != nil {
r.Errorf("error %v", err)
}
}
case _ = <-r.shutdown:
// receive message from shutdown channel
// will stop current thread and stop ticker to prevent thread leak
ticker.Stop()
return
}
}
}()
return nil
}
func (r *etcd) register(addr string, ttl int) error {
leaseResp, err := r.cli.Grant(context.Background(), int64(ttl))
if err != nil {
return err
}
_, err = r.cli.Put(context.Background(), "/"+naming.Prefix+"/"+r.serviceName+"/"+addr, addr, clientv3.WithLease(leaseResp.ID))
if err != nil {
return err
}
_, err = r.cli.KeepAlive(context.Background(), leaseResp.ID)
if err != nil {
return err
}
return nil
}
// UnRegister deletes itself in etcd storage
// also stop watch goroutine and ticker inside it
func (r *etcd) UnRegister(addr string) error {
_, _ = r.cli.Delete(context.Background(), "/"+naming.Prefix+"/"+r.serviceName+"/"+addr)
r.shutdown <- "stop"
return nil
}