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 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
| package main
import ( "fmt" "github.com/samuel/go-zookeeper/zk" "log" "time" )
func callback(event zk.Event) { fmt.Println("###########################") fmt.Println("path: ", event.Path) fmt.Println("type: ", event.Type.String()) fmt.Println("state: ", event.State.String()) fmt.Println("---------------------------") }
func initZk() (*zk.Conn, error) { eventCallbackOption := zk.WithEventCallback(callback) servers := []string{"127.0.0.1:2181"} conn, _, err := zk.Connect(servers, time.Second*5, eventCallbackOption) return conn, err }
func add(conn *zk.Conn, path string, data []byte, flags int32) error { acls := zk.WorldACL(zk.PermAll) _, err := conn.Create(path, data, flags, acls)
return err }
func delete(conn *zk.Conn, path string) error { _, stat, err := conn.Get(path) if err != nil { return err } err = conn.Delete(path, stat.Version) return err }
func listenOne(conn *zk.Conn, path string) error { _, _, _, err := conn.ExistsW(path) return err }
func main() { conn, err := initZk() defer conn.Close() if err != nil { fmt.Println(err) return }
path := "/dawn111" data := []byte("hello world")
err = listenOne(conn, path) if err != nil { log.Println(err) } err = add(conn, path, data, 0) if err != nil { log.Println("create failed, err:", err) } else { log.Println("创建数据成功!") }
err = listenOne(conn, path) if err != nil { log.Println(err) } err = delete(conn, path) if err != nil { log.Printf("delete failed for path %s, err: %v\n", path, err) } else { log.Println("删除数据成功!") }
}
|