代码拉取完成,页面将自动刷新
package etcd
import (
"context"
"gitee.com/h79/goutils/common/system"
"gitee.com/h79/goutils/discovery/service"
"gitee.com/h79/goutils/discovery/watch"
"go.etcd.io/etcd/api/v3/mvccpb"
clientv3 "go.etcd.io/etcd/client/v3"
)
type Watcher struct {
client *clientv3.Client
wc watch.Chan
ctx context.Context
cancel context.CancelFunc
}
func NewWatcher(client *clientv3.Client, sizeChan int) *Watcher {
ctx, cancel := context.WithCancel(context.Background())
return &Watcher{
client: client,
wc: make(watch.Chan, sizeChan),
cancel: cancel,
ctx: ctx,
}
}
func (watcher *Watcher) Watch(key watch.Key) (watch.Chan, error) {
wc := watcher.client.Watch(context.Background(), key.ToKey(), clientv3.WithPrefix())
system.ChildRunning(func() {
select {
case resp := <-wc:
for _, ev := range resp.Events {
data := service.Data{Key: service.NewKey(string(ev.Kv.Key)), Value: string(ev.Kv.Value)}
switch ev.Type {
case mvccpb.PUT:
watcher.wc <- watch.NewChanged(data, watch.Put)
case mvccpb.DELETE:
watcher.wc <- watch.NewChanged(data, watch.Delete)
}
}
case <-watcher.ctx.Done():
return
case <-system.Closed():
return
}
})
return watcher.wc, nil
}
func (watcher *Watcher) Changed(cmd watch.Changed) {
watcher.wc <- cmd
}
func (watcher *Watcher) Stop() error {
watcher.cancel()
return nil
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。