1 Star 0 Fork 0

llakcs / agile-go

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
watcher.go 2.01 KB
一键复制 编辑 原始数据 按行查看 历史
llakcs 提交于 2024-01-31 16:54 . 第一次提交
package nacos
import (
"context"
"fmt"
"gitee.com/llakcs/agile-go/registry"
"github.com/nacos-group/nacos-sdk-go/v2/clients/naming_client"
"github.com/nacos-group/nacos-sdk-go/v2/model"
"github.com/nacos-group/nacos-sdk-go/v2/vo"
)
type watcher struct {
serviceName string
clusters []string
groupName string
ctx context.Context
cancel context.CancelFunc
watchChan chan struct{}
cli naming_client.INamingClient
kind string
}
func newWatcher(ctx context.Context, cli naming_client.INamingClient, serviceName, groupName, kind string, clusters []string) (*watcher, error) {
w := &watcher{
serviceName: serviceName,
clusters: clusters,
groupName: groupName,
cli: cli,
kind: kind,
watchChan: make(chan struct{}, 1),
}
w.ctx, w.cancel = context.WithCancel(ctx)
e := w.cli.Subscribe(&vo.SubscribeParam{
ServiceName: serviceName,
Clusters: clusters,
GroupName: groupName,
SubscribeCallback: func(services []model.Instance, err error) {
w.watchChan <- struct{}{}
},
})
return w, e
}
func (w *watcher) Next() ([]*registry.ServiceInstance, error) {
select {
case <-w.ctx.Done():
return nil, w.ctx.Err()
case <-w.watchChan:
}
res, err := w.cli.GetService(vo.GetServiceParam{
ServiceName: w.serviceName,
GroupName: w.groupName,
Clusters: w.clusters,
})
if err != nil {
return nil, err
}
items := make([]*registry.ServiceInstance, 0, len(res.Hosts))
for _, in := range res.Hosts {
kind := w.kind
if k, ok := in.Metadata["kind"]; ok {
kind = k
}
items = append(items, &registry.ServiceInstance{
ID: in.InstanceId,
Name: res.Name,
Weight: int64(in.Weight),
Version: in.Metadata["version"],
Metadata: in.Metadata,
Endpoints: []string{fmt.Sprintf("%s://%s:%d", kind, in.Ip, in.Port)},
})
}
return items, nil
}
func (w *watcher) Stop() error {
w.cancel()
return w.cli.Unsubscribe(&vo.SubscribeParam{
ServiceName: w.serviceName,
GroupName: w.groupName,
Clusters: w.clusters,
})
}
1
https://gitee.com/llakcs/agile-go.git
git@gitee.com:llakcs/agile-go.git
llakcs
agile-go
agile-go
v1.0.4

搜索帮助