watch.go 1.03 KB
Newer Older
hujiebin's avatar
hujiebin committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
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)
		}
	}
}