go-zero/rpcx/internal/resolver/resolver.go

70 lines
1.2 KiB
Go
Raw Normal View History

2020-07-30 20:09:45 +08:00
package resolver
2020-07-31 17:33:08 +08:00
import (
2020-08-06 20:55:38 +08:00
"fmt"
"strings"
2020-07-31 17:33:08 +08:00
"zero/core/discov"
"google.golang.org/grpc/resolver"
)
2020-07-30 20:09:45 +08:00
2020-08-06 20:55:38 +08:00
const (
DiscovScheme = "discov"
EndpointSep = ","
2020-08-06 23:06:26 +08:00
subsetSize = 36
2020-08-06 20:55:38 +08:00
)
var builder discovBuilder
2020-08-04 11:59:39 +08:00
2020-08-06 20:55:38 +08:00
type discovBuilder struct{}
2020-07-31 17:33:08 +08:00
2020-08-04 11:59:39 +08:00
func (b *discovBuilder) Scheme() string {
2020-08-06 20:55:38 +08:00
return DiscovScheme
2020-08-04 11:59:39 +08:00
}
func (b *discovBuilder) Build(target resolver.Target, cc resolver.ClientConn, opts resolver.BuildOptions) (
2020-07-31 17:33:08 +08:00
resolver.Resolver, error) {
2020-08-06 20:55:38 +08:00
if target.Scheme != DiscovScheme {
return nil, fmt.Errorf("bad scheme: %s", target.Scheme)
}
hosts := strings.Split(target.Authority, EndpointSep)
sub, err := discov.NewSubscriber(hosts, target.Endpoint)
2020-07-31 17:33:08 +08:00
if err != nil {
return nil, err
}
2020-08-06 20:55:38 +08:00
update := func() {
2020-07-31 17:33:08 +08:00
var addrs []resolver.Address
2020-08-06 23:06:26 +08:00
for _, val := range subset(sub.Values(), subsetSize) {
2020-07-31 17:33:08 +08:00
addrs = append(addrs, resolver.Address{
Addr: val,
})
}
2020-08-04 11:59:39 +08:00
cc.UpdateState(resolver.State{
2020-07-31 17:33:08 +08:00
Addresses: addrs,
})
2020-08-06 20:55:38 +08:00
}
sub.AddListener(update)
update()
2020-07-31 17:33:08 +08:00
2020-08-04 11:59:39 +08:00
return &discovResolver{
cc: cc,
}, nil
2020-07-31 17:33:08 +08:00
}
2020-08-04 11:59:39 +08:00
type discovResolver struct {
cc resolver.ClientConn
2020-07-31 17:33:08 +08:00
}
2020-08-04 11:59:39 +08:00
func (r *discovResolver) Close() {
2020-07-30 20:09:45 +08:00
}
2020-08-04 11:59:39 +08:00
func (r *discovResolver) ResolveNow(options resolver.ResolveNowOptions) {
2020-07-30 20:09:45 +08:00
}
2020-08-06 20:55:38 +08:00
func RegisterResolver() {
resolver.Register(&builder)
2020-07-30 20:09:45 +08:00
}