https://pkg.go.dev/github.com/samuel/go-zookeeper@v0.0.0-20201211165307-7117e9ea2414/zk
go get github.com/samuel/go-zookeeper
package main
import (
"fmt"
"time"
"github.com/samuel/go-zookeeper/zk"
)
func getConn() *zk.Conn {
var hosts = []string{
"192.168.74.138:2181"} //server端ip:host
conn, _, err := zk.Connect(hosts, time.Second*5)
defer conn.Close()
if err != nil {
fmt.Println(err)
return nil
} else {
fmt.Println("zookeeper 连接成功!")
return conn
}
}
func main() {
conn := getConn()
fmt.Println(&conn)
}
运行结果:
[Running] go run "e:\golang开发学习\test_zk_golang\test.go"
zookeeper 连接成功!
2022/09/13 13:10:15 Connected to 192.168.74.128:2181
2022/09/13 13:10:15 authenticated: id=144115412815642627, timeout=4000
2022/09/13 13:10:15 re-submitting `0` credentials after reconnect
0xc000006028
[Done] exited with code=0 in 2.261 seconds
func (c *Conn) Create(path string, data []byte, flags int32, acl []ACL) (string, error)
//path:路径
//data:数据
// flags有4中取值:
// 0:永久,除非手动删除
// zk.FlagEphemeral = 1:短暂,session断开则该节点也会被删除
// zk.FlagSequence = 2:会自动还在节点后面添加序号
// 3:Ephemeral和Sequence,即短暂且自动添加序号
//acl:权限
实例演示:
package main
import (
"fmt"
"time"
"github.com/samuel/go-zookeeper/zk"
)
func getConn() *zk.Conn {
var hosts = []string{
"192.168.74.128:2181"} //server端host
conn, _, err := zk.Connect(hosts, time.Second*1)