-
Notifications
You must be signed in to change notification settings - Fork 222
/
watcher.go
78 lines (68 loc) 路 1.62 KB
/
watcher.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
package etcd
import (
"context"
clientv3 "go.etcd.io/etcd/client/v3"
"github.com/go-eagle/eagle/pkg/registry"
)
var _ registry.Watcher = &watcher{}
type watcher struct {
key string
ctx context.Context
cancel context.CancelFunc
watchChan clientv3.WatchChan
watcher clientv3.Watcher
kv clientv3.KV
first bool
serviceName string
}
func newWatcher(ctx context.Context, key, name string, client *clientv3.Client) (*watcher, error) {
w := &watcher{
key: key,
watcher: clientv3.NewWatcher(client),
kv: clientv3.NewKV(client),
first: true,
serviceName: name,
}
w.ctx, w.cancel = context.WithCancel(ctx)
w.watchChan = w.watcher.Watch(w.ctx, key, clientv3.WithPrefix(), clientv3.WithRev(0))
err := w.watcher.RequestProgress(context.Background())
if err != nil {
return nil, err
}
return w, nil
}
func (w *watcher) Next() ([]*registry.ServiceInstance, error) {
if w.first {
item, err := w.getInstance()
w.first = false
return item, err
}
select {
case <-w.ctx.Done():
return nil, w.ctx.Err()
case <-w.watchChan:
return w.getInstance()
}
}
func (w *watcher) Stop() error {
w.cancel()
return w.watcher.Close()
}
func (w *watcher) getInstance() ([]*registry.ServiceInstance, error) {
resp, err := w.kv.Get(w.ctx, w.key, clientv3.WithPrefix())
if err != nil {
return nil, err
}
items := make([]*registry.ServiceInstance, 0, len(resp.Kvs))
for _, kv := range resp.Kvs {
si, err := unmarshal(kv.Value)
if err != nil {
return nil, err
}
if si.Name != w.serviceName {
continue
}
items = append(items, si)
}
return items, nil
}