package consul import ( "fmt" consulapi "github.com/hashicorp/consul/api" "hilo-userProxy/common/mylogrus" "time" ) func RegisterWatcher(serviceName string, cb func(addr []string)) { ticker := time.NewTicker(time.Minute) defer ticker.Stop() for { select { case <-ticker.C: client, err := consulapi.NewClient(consulapi.DefaultConfig()) //非默认情况下需要设置实际的参数 if err != nil { mylogrus.MyLog.Errorf("RegisterToConsul Fail:%v", err) continue } if client == nil { mylogrus.MyLog.Errorf("Fail to get consul client.") continue } cataLog := client.Catalog() if cataLog == nil { mylogrus.MyLog.Errorf("No catalog.") continue } services, _, err := cataLog.Service(serviceName, "", nil) if err != nil { mylogrus.MyLog.Errorf("%v", err) continue } var addr []string for _, v := range services { addr = append(addr, fmt.Sprintf("%s:%d", v.ServiceAddress, v.ServicePort)) } mylogrus.MyLog.Infof("%s check addr%v", serviceName, addr) cb(addr) } } }