如何判断zookeeper cluster是否可用
还没有找到更好的办法,这个办法很土,就是客户端发起命令一个list命令,看看能不能正确得到结果;list的目标可以是根路径(/),或者其他内置的路径,例如(/zookeeper)。
下面是golang的例子,使用了github.com/samuel/go-zookeeper/zk库文件。
package main
import (
"log"
"time"
"github.com/samuel/go-zookeeper/zk"
)
var ZOOKEEPER_SERVERS = []string { "zookeeper1.example.com:2181",
"zookeeper2.example.com:2181",
"zookeeper3.example.com:2181"}
func main() {
if checkZookeeper() {
log.Printf("Check zookeeper status success\n")
} else {
log.Printf("Check zookeeper status failure\n")
}
}
func checkZookeeper() bool {
conn, events, err := zk.Connect(ZOOKEEPER_SERVERS, time.Second)
if err != nil {
log.Printf("ERROR: Cannot connect to zk server, err=[%v]\n", err)
return false
}
defer conn.Close()
Loop:
for event := range events {
switch event.State {
case zk.StateConnecting, zk.StateConnected :
//continue
case zk.StateDisconnected:
log.Printf("ERROR: zk status: disconnected\n")
return false
case zk.StateHasSession:
break Loop
default:
log.Printf("ERROR: zk status: %s\n", event.State)
return false
}
}
children, _, err := conn.Children("/zookeeper")
if err != nil {
log.Printf("ERROR: Unable to list children, err=[%v]\n", err)
return false
}
log.Printf("Get total keys count=[%d]\n", len(children))
for i, child := range children {
log.Printf("\tChild[%d]: [%s]\n", i, child)
}
return true
}
有疑问加站长微信联系(非本文作者)