-
Notifications
You must be signed in to change notification settings - Fork 0
/
zk.go
47 lines (38 loc) · 936 Bytes
/
zk.go
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
44
45
46
47
package main
import (
"time"
"github.com/samuel/go-zookeeper/zk"
"github.com/xgfone/go-tools/lifecycle"
)
// ZkLoggerFunc is a function wrapper of Zk Logger, which converts a function
// to the type of zk.Logger.
type ZkLoggerFunc func(string, ...interface{})
// Printf implements the interface of zk.Logger.
func (l ZkLoggerFunc) Printf(format string, args ...interface{}) {
l(format, args...)
}
// ZkClient represents a client of a ZooKeeper connection.
type ZkClient struct {
*zk.Conn
}
// NewZkClient returns a new ZkClient.
func NewZkClient(addrs []string, timeout int, logger zk.Logger) (zc ZkClient, err error) {
c, ev, err := zk.Connect(addrs, time.Duration(timeout)*time.Second)
if err != nil {
return
}
if logger != nil {
c.SetLogger(logger)
}
lifecycle.Register(func() { c.Close() })
zc.Conn = c
go func() {
for {
if _, ok := <-ev; !ok {
lifecycle.Stop()
return
}
}
}()
return
}