-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwatch.go
88 lines (77 loc) · 2.08 KB
/
watch.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
package eetcd
import (
"context"
"sync"
"github.com/gotomicro/ego/core/elog"
"go.etcd.io/etcd/api/v3/mvccpb"
"go.etcd.io/etcd/client/v3"
)
// Watch A watch only tells the latest revision
type Watch struct {
revision int64
cancel context.CancelFunc
eventChan chan *clientv3.Event
lock *sync.RWMutex
incipientKVs []*mvccpb.KeyValue
}
// C ...
func (w *Watch) C() chan *clientv3.Event {
return w.eventChan
}
// IncipientKeyValues incipient key and values
func (w *Watch) IncipientKeyValues() []*mvccpb.KeyValue {
return w.incipientKVs
}
// WatchPrefix 监听某个key
func (c *Component) WatchPrefix(ctx context.Context, prefix string) (*Watch, error) {
resp, err := c.Get(ctx, prefix, clientv3.WithPrefix())
if err != nil {
return nil, err
}
var w = &Watch{
revision: resp.Header.Revision,
eventChan: make(chan *clientv3.Event, 100),
incipientKVs: resp.Kvs,
}
go func() {
ctx, cancel := context.WithCancel(context.Background())
w.cancel = cancel
rch := c.Client.Watch(ctx, prefix, clientv3.WithPrefix(), clientv3.WithCreatedNotify(), clientv3.WithRev(w.revision))
for {
for n := range rch {
if n.CompactRevision > w.revision {
w.revision = n.CompactRevision
}
if n.Header.GetRevision() > w.revision {
w.revision = n.Header.GetRevision()
}
if err := n.Err(); err != nil {
c.logger.Error("watch error", elog.FieldErr(err), elog.FieldAddr(prefix))
continue
}
for _, ev := range n.Events {
select {
case w.eventChan <- ev:
default:
c.logger.Error("watch etcd with prefix", elog.Any("err", "block event chan, drop event message"))
}
}
}
ctx, cancel := context.WithCancel(context.Background())
w.cancel = cancel
if w.revision > 0 {
rch = c.Watch(ctx, prefix, clientv3.WithPrefix(), clientv3.WithCreatedNotify(), clientv3.WithRev(w.revision))
} else {
rch = c.Watch(ctx, prefix, clientv3.WithPrefix(), clientv3.WithCreatedNotify())
}
}
}()
return w, nil
}
// Close watch
func (w *Watch) Close() error {
if w.cancel != nil {
w.cancel()
}
return nil
}