go-zookeeper Connect 返回一个无效的连接

huangapple go评论106阅读模式
英文:

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
}

huangapple
  • 本文由 发表于 2017年1月8日 04:03:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/41525907.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定