example_resolver.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. package clientImpl
  2. import (
  3. "../constants"
  4. "google.golang.org/grpc/resolver"
  5. )
  6. // resolver工厂实现类
  7. type ExampleResolverBuilder struct{}
  8. func (*ExampleResolverBuilder) Build(target resolver.Target, cc resolver.ClientConn, opts resolver.BuildOptions) (resolver.Resolver, error) {
  9. r := &exampleResolver{
  10. target: target,
  11. cc: cc,
  12. addressStore: map[string][]string{
  13. constants.ExampleServiceName: constants.ExampleEndpoints, // 服务命名与实际服务终结点列表的对应关系 "go-example": ["localhost:50051", "localhost:50052"]
  14. },
  15. }
  16. r.start()
  17. return r, nil
  18. }
  19. func (*ExampleResolverBuilder) Scheme() string { return constants.ExampleScheme } // "grpc"
  20. // resolver实现类
  21. type exampleResolver struct {
  22. target resolver.Target
  23. cc resolver.ClientConn
  24. addressStore map[string][]string
  25. }
  26. func (r *exampleResolver) start() {
  27. addrList := r.addressStore[r.target.Endpoint]
  28. addresses := make([]resolver.Address, len(addrList))
  29. for i, s := range addrList {
  30. addresses[i] = resolver.Address{Addr: s}
  31. }
  32. r.cc.UpdateState(resolver.State{Addresses: addresses})
  33. }
  34. func (*exampleResolver) ResolveNow(resolver.ResolveNowOptions) {}
  35. func (*exampleResolver) Close() {}