英文:
go-zookeeper Connect returns without a valid connection
问题
我对zookeeper有一个问题,我正在尝试在Go语言中使用zookeeper实现简单的服务发现,我正在使用go-zookeeper库:https://github.com/samuel/go-zookeeper
我的问题是,当我使用以下代码连接到zookeeper时:
zoo_keeper, _, err := zk.Connect(s, time.Second)
该函数会立即返回,并且没有报告任何错误,但实际上还没有建立有效的连接。现在,例如,如果我想创建znode,我需要检查什么以确保在执行之前我有一个有效的连接?
英文:
I have a question regarding zookeeper, I am trying to implement simple service discovery with zookeeper in go, I am using go-zookeeper: https://github.com/samuel/go-zookeeper
My question is whenever I connect to zookeeper using for example:
zoo_keeper, _, err := zk.Connect(s, time.Second)
the function returns immediately and no error is reported, but there is no actual valid connection yet. Now for example if I want to create znodes, what do I need to check to make sure I have a valid connection before doing so?
答案1
得分: 4
在尝试了几种方法之后,感谢Imesha的建议,我可以通过使用通道来实现我想要的效果。以下是我的示例代码。
func zk_connect(zk_server string) (*zk.Conn, error) {
zoo_keeper, session, err := zk.Connect([]string{zk_server}, time.Second)
if err != nil {
return nil, err
}
for event := range session {
if event.State == zk.StateConnected {
log.Printf("zookeeper State: %s\n", event.State)
break
}
}
return zoo_keeper, nil
}
英文:
After trying several things, and thanks to the suggestion from Imesha, I can achieve what I wanted using channels. Below is my sample code.
func zk_connect(zk_server string) (*zk.Conn, error) {
zoo_keeper, session, err := zk.Connect([]string{zk_server}, time.Second)
if err != nil {
return nil, err
}
for event := range session {
if event.State == zk.StateConnected {
log.Printf("zookeeper State: %s\n", event.State)
break
}
}
return zoo_keeper, nil
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论