go-zero/zrpc/resolver/internal/discovbuilder.go

46 lines
1.0 KiB
Go
Raw Normal View History

package internal
2020-08-18 18:36:44 +08:00
import (
"strings"
"github.com/zeromicro/go-zero/core/discov"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/zrpc/resolver/internal/targets"
2020-08-18 18:36:44 +08:00
"google.golang.org/grpc/resolver"
)
type discovBuilder struct{}
func (b *discovBuilder) Build(target resolver.Target, cc resolver.ClientConn, _ resolver.BuildOptions) (
2020-08-18 18:36:44 +08:00
resolver.Resolver, error) {
hosts := strings.FieldsFunc(targets.GetAuthority(target), func(r rune) bool {
2020-08-25 18:36:30 +08:00
return r == EndpointSepChar
2020-08-20 15:35:13 +08:00
})
sub, err := discov.NewSubscriber(hosts, targets.GetEndpoints(target))
2020-08-18 18:36:44 +08:00
if err != nil {
return nil, err
}
update := func() {
var addrs []resolver.Address
for _, val := range subset(sub.Values(), subsetSize) {
addrs = append(addrs, resolver.Address{
Addr: val,
})
}
if err := cc.UpdateState(resolver.State{
2020-08-18 18:36:44 +08:00
Addresses: addrs,
}); err != nil {
logx.Error(err)
}
2020-08-18 18:36:44 +08:00
}
sub.AddListener(update)
update()
return &nopResolver{cc: cc}, nil
}
func (b *discovBuilder) Scheme() string {
2020-08-18 18:36:44 +08:00
return DiscovScheme
}