2021-12-01 20:22:15 +08:00
|
|
|
package internal
|
2020-08-18 18:36:44 +08:00
|
|
|
|
|
|
|
import (
|
|
|
|
"strings"
|
|
|
|
|
2022-01-04 15:51:32 +08:00
|
|
|
"github.com/zeromicro/go-zero/core/discov"
|
|
|
|
"github.com/zeromicro/go-zero/core/logx"
|
2022-04-27 21:34:54 +08:00
|
|
|
"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{}
|
|
|
|
|
2021-11-28 20:08:18 +08:00
|
|
|
func (b *discovBuilder) Build(target resolver.Target, cc resolver.ClientConn, _ resolver.BuildOptions) (
|
2020-08-18 18:36:44 +08:00
|
|
|
resolver.Resolver, error) {
|
2022-04-27 21:34:54 +08:00
|
|
|
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
|
|
|
})
|
2022-04-27 21:34:54 +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,
|
|
|
|
})
|
|
|
|
}
|
2021-09-04 10:27:08 +08:00
|
|
|
if err := cc.UpdateState(resolver.State{
|
2020-08-18 18:36:44 +08:00
|
|
|
Addresses: addrs,
|
2021-09-04 10:27:08 +08:00
|
|
|
}); err != nil {
|
|
|
|
logx.Error(err)
|
|
|
|
}
|
2020-08-18 18:36:44 +08:00
|
|
|
}
|
|
|
|
sub.AddListener(update)
|
|
|
|
update()
|
|
|
|
|
|
|
|
return &nopResolver{cc: cc}, nil
|
|
|
|
}
|
|
|
|
|
2021-09-04 10:27:08 +08:00
|
|
|
func (b *discovBuilder) Scheme() string {
|
2020-08-18 18:36:44 +08:00
|
|
|
return DiscovScheme
|
|
|
|
}
|