discovbuilder.go 860 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. package resolver
  2. import (
  3. "strings"
  4. "github.com/tal-tech/go-zero/core/discov"
  5. "google.golang.org/grpc/resolver"
  6. )
  7. type discovBuilder struct{}
  8. func (d *discovBuilder) Build(target resolver.Target, cc resolver.ClientConn, opts resolver.BuildOptions) (
  9. resolver.Resolver, error) {
  10. hosts := strings.FieldsFunc(target.Authority, func(r rune) bool {
  11. return r == EndpointSepChar
  12. })
  13. sub, err := discov.NewSubscriber(hosts, target.Endpoint)
  14. if err != nil {
  15. return nil, err
  16. }
  17. update := func() {
  18. var addrs []resolver.Address
  19. for _, val := range subset(sub.Values(), subsetSize) {
  20. addrs = append(addrs, resolver.Address{
  21. Addr: val,
  22. })
  23. }
  24. cc.UpdateState(resolver.State{
  25. Addresses: addrs,
  26. })
  27. }
  28. sub.AddListener(update)
  29. update()
  30. return &nopResolver{cc: cc}, nil
  31. }
  32. func (d *discovBuilder) Scheme() string {
  33. return DiscovScheme
  34. }