代码拉取完成,页面将自动刷新
package consul
import (
"context"
"gitee.com/h79/goutils/common"
"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
go func() {
defer common.Recover()
err = wp.RunWithClientAndHclog(watcher.client, nil)
if err != 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
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。