-
-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
watcher.go
81 lines (73 loc) · 1.83 KB
/
watcher.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
package registry
import (
"context"
"fmt"
"github.com/go-kratos/kratos/v2/registry"
"github.com/nacos-group/nacos-sdk-go/clients/naming_client"
"github.com/nacos-group/nacos-sdk-go/model"
"github.com/nacos-group/nacos-sdk-go/vo"
)
var (
_ registry.Watcher = (*watcher)(nil)
)
type watcher struct {
serviceName string
clusters []string
groupName string
ctx context.Context
cancel context.CancelFunc
watchChan chan bool
cli naming_client.INamingClient
}
func newWatcher(ctx context.Context, cli naming_client.INamingClient, serviceName string, groupName string, clusters []string) (*watcher, error) {
w := &watcher{
serviceName: serviceName,
clusters: clusters,
groupName: groupName,
cli: cli,
watchChan: make(chan bool, 1),
}
w.ctx, w.cancel = context.WithCancel(ctx)
e := w.cli.Subscribe(&vo.SubscribeParam{
ServiceName: serviceName,
Clusters: clusters,
GroupName: groupName,
SubscribeCallback: func(services []model.SubscribeService, err error) {
w.watchChan <- true
},
})
return w, e
}
func (w *watcher) Next() ([]*registry.ServiceInstance, error) {
for {
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
}
var items []*registry.ServiceInstance
for _, in := range res.Hosts {
items = append(items, ®istry.ServiceInstance{
ID: in.InstanceId,
Name: res.Name,
Version: in.Metadata["version"],
Metadata: in.Metadata,
Endpoints: []string{fmt.Sprintf("%s://%s:%d", in.Metadata["kind"], in.Ip, in.Port)},
})
}
return items, nil
}
}
func (w *watcher) Stop() error {
w.cancel()
//close
return nil
}