-
Notifications
You must be signed in to change notification settings - Fork 0
/
resolver.go
executable file
·81 lines (70 loc) · 2.1 KB
/
resolver.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 nacos
import (
"context"
"fmt"
"sort"
"github.com/nacos-group/nacos-sdk-go/v2/common/logger"
"github.com/nacos-group/nacos-sdk-go/v2/model"
"github.com/zeromicro/go-zero/core/logx"
"google.golang.org/grpc/resolver"
)
type resolvr struct {
cancelFunc context.CancelFunc
}
func (r *resolvr) ResolveNow(resolver.ResolveNowOptions) {}
// Close closes the resolver.
func (r *resolvr) Close() {
r.cancelFunc()
}
type watcher struct {
ctx context.Context
cancel context.CancelFunc
out chan<- []string
}
func newWatcher(ctx context.Context, cancel context.CancelFunc, out chan<- []string) *watcher {
return &watcher{
ctx: ctx,
cancel: cancel,
out: out,
}
}
func (nw *watcher) CallBackHandle(services []model.Instance, err error) {
if err != nil {
logger.Error("[Nacos resolver] watcher call back handle error:%v", err)
return
}
ee := make([]string, 0, len(services))
for _, s := range services {
if s.Metadata != nil && s.Metadata["gRPC_port"] != "" {
ee = append(ee, fmt.Sprintf("%s:%s", s.Ip, s.Metadata["gRPC_port"]))
} else {
ee = append(ee, fmt.Sprintf("%s:%d", s.Ip, s.Port))
}
}
nw.out <- ee
}
func populateEndpoints(ctx context.Context, clientConn resolver.ClientConn, input <-chan []string) {
for {
select {
case cc := <-input:
connsSet := make(map[string]struct{}, len(cc))
for _, c := range cc {
connsSet[c] = struct{}{}
}
conns := make([]resolver.Address, 0, len(connsSet))
for c := range connsSet {
conns = append(conns, resolver.Address{Addr: c})
}
sort.Sort(byAddressString(conns)) // Don't replace the same address list in the balancer
_ = clientConn.UpdateState(resolver.State{Addresses: conns})
case <-ctx.Done():
logx.Info("[Nacos resolver] Watch has been finished")
return
}
}
}
// byAddressString sorts resolver.Address by Address Field sorting in increasing order.
type byAddressString []resolver.Address
func (p byAddressString) Len() int { return len(p) }
func (p byAddressString) Less(i, j int) bool { return p[i].Addr < p[j].Addr }
func (p byAddressString) Swap(i, j int) { p[i], p[j] = p[j], p[i] }