1 Star 0 Fork 0

h79/goutils

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
watcher.go 1.55 KB
一键复制 编辑 原始数据 按行查看 历史
package consul
import (
"context"
"gitee.com/h79/goutils/common/system"
"gitee.com/h79/goutils/discovery/service"
discoveryWatch "gitee.com/h79/goutils/discovery/watch"
consul2 "github.com/hashicorp/consul/api"
"github.com/hashicorp/consul/api/watch"
)
type Watcher struct {
client *consul2.Client
wc discoveryWatch.Chan
wp *watch.Plan
ctx context.Context
cancel context.CancelFunc
}
func NewWatcher(client *consul2.Client, sizeChan int) (*Watcher, error) {
ctx, cancel := context.WithCancel(context.Background())
watcher := &Watcher{
client: client,
wc: make(discoveryWatch.Chan, sizeChan),
wp: nil,
ctx: ctx,
cancel: cancel,
}
return watcher, nil
}
func (watcher *Watcher) Watch(key discoveryWatch.Key) (discoveryWatch.Chan, error) {
wp, err := watch.Parse(key.ToMap())
if err != nil {
return nil, err
}
watcher.wp = wp
wp.Handler = func(idx uint64, data interface{}) {
if data == nil {
return
}
sulkv, ok := data.(consul2.KVPairs)
if !ok {
return
}
for _, pairs := range sulkv {
da := service.Data{Key: service.NewKey(pairs.Key), Value: string(pairs.Value)}
watcher.wc <- discoveryWatch.Changed{
D: da,
Cmd: discoveryWatch.Put,
}
}
}
//is a blocking
system.ChildRunning(func() {
_ = wp.RunWithClientAndHclog(watcher.client, nil)
})
return watcher.wc, nil
}
func (watcher *Watcher) Changed(cmd discoveryWatch.Changed) {
watcher.wc <- cmd
}
func (watcher *Watcher) Stop() error {
if watcher.wp != nil {
watcher.wp.Stop()
watcher.wp = nil
}
watcher.cancel()
return nil
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/h79/goutils.git
git@gitee.com:h79/goutils.git
h79
goutils
goutils
v1.8.68

搜索帮助

A270a887 8829481 3d7a4017 8829481