watch.go 1.04 KB
Newer Older
hujiebin's avatar
hujiebin committed
1 2 3 4 5 6
package consul

import (
	"fmt"
	"git.hilo.cn/hilo-common/mylogrus"
	consulapi "github.com/hashicorp/consul/api"
hujiebin's avatar
hujiebin committed
7
	"time"
hujiebin's avatar
hujiebin committed
8 9
)

hujiebin's avatar
hujiebin committed
10 11 12 13 14 15 16 17 18 19
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
hujiebin's avatar
hujiebin committed
20
			}
hujiebin's avatar
hujiebin committed
21 22 23
			if client == nil {
				mylogrus.MyLog.Errorf("Fail to get consul client.")
				continue
hujiebin's avatar
hujiebin committed
24
			}
hujiebin's avatar
hujiebin committed
25 26 27 28 29 30 31 32 33 34 35 36 37
			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))
hujiebin's avatar
hujiebin committed
38
			}
hujiebin's avatar
hujiebin committed
39 40
			mylogrus.MyLog.Infof("%s check addr%v", serviceName, addr)
			cb(addr)
hujiebin's avatar
hujiebin committed
41 42 43
		}
	}
}