github.com/jtzjtz/kit@v1.0.2/balance/resolve.go (about) 1 package balance 2 3 import ( 4 "github.com/nacos-group/nacos-sdk-go/model" 5 "github.com/nacos-group/nacos-sdk-go/util" 6 "github.com/nacos-group/nacos-sdk-go/vo" 7 "google.golang.org/grpc/resolver" 8 "log" 9 "strconv" 10 ) 11 12 const schema = "sq" 13 14 type NacosResolver struct { 15 nacosConf NacosConfig 16 cc resolver.ClientConn 17 } 18 19 // NewResolver initialize an etcd client 20 func NewResolver(nacosConf NacosConfig) resolver.Builder { 21 return &NacosResolver{nacosConf: nacosConf} 22 } 23 24 func (r *NacosResolver) Build(target resolver.Target, cc resolver.ClientConn, opts resolver.BuildOptions) (resolver.Resolver, error) { 25 var err error 26 27 if cli == nil { 28 cli, err = createNacosClient(r.nacosConf) 29 if err != nil { 30 return nil, err 31 } 32 } 33 r.cc = cc 34 35 go r.watch(target.Endpoint, target.Scheme) 36 return r, nil 37 } 38 39 func (r NacosResolver) Scheme() string { 40 return r.nacosConf.GroupName 41 } 42 43 func (r NacosResolver) ResolveNow(rn resolver.ResolveNowOptions) { 44 45 log.Println(r.nacosConf.GroupName + "ResolveNow") 46 } 47 48 // Close closes the resolver. 49 func (r NacosResolver) Close() { 50 log.Println("Close") 51 } 52 53 func (r *NacosResolver) watch(serviceName string, group string) { 54 var addrList []resolver.Address 55 56 getResp, err := cli.SelectAllInstances(vo.SelectAllInstancesParam{ 57 ServiceName: serviceName, 58 GroupName: group, 59 }) 60 if err != nil { 61 log.Println(err) 62 } else { 63 for _, instance := range getResp { 64 addr := instance.Ip + ":" + strconv.FormatUint(instance.Port, 10) 65 if instance.Enable { 66 addrList = append(addrList, resolver.Address{Addr: addr, ServerName: instance.ServiceName}) 67 } 68 } 69 70 } 71 r.cc.UpdateState(resolver.State{Addresses: addrList}) 72 subScribeParam := &vo.SubscribeParam{ 73 ServiceName: serviceName, 74 //Clusters: []string{"cluster-b"}, 75 GroupName: group, 76 SubscribeCallback: func(services []model.SubscribeService, err error) { 77 log.Printf("订阅 return services:%s \n\n", util.ToJsonString(services)) 78 var addrListNew []resolver.Address 79 for _, eventService := range services { 80 addr := eventService.Ip + ":" + strconv.FormatUint(eventService.Port, 10) 81 if eventService.Enable { 82 addrListNew = append(addrListNew, resolver.Address{Addr: addr, ServerName: eventService.ServiceName}) 83 } 84 } 85 r.cc.UpdateState(resolver.State{Addresses: addrListNew}) 86 log.Printf("新的address list:%s \n\n", util.ToJsonString(addrListNew)) 87 88 }, 89 } 90 cli.Subscribe(subScribeParam) 91 92 }