1. 基本操作测试

简单的例子来测试下基本的操作:

  1. package main
  2. /**
  3. 客户端doc地址:github.com/samuel/go-zookeeper/zk
  4. **/
  5. import (
  6. "fmt"
  7. "time"
  8. zk "github.com/samuel/go-zookeeper/zk"
  9. )
  10. /**
  11. * 获取一个zk连接
  12. * @return {[type]}
  13. */
  14. func getConnect(zkList []string) (conn *zk.Conn) {
  15. conn, _, err := zk.Connect(zkList, 10*time.Second)
  16. if err != nil {
  17. fmt.Println(err)
  18. }
  19. return
  20. }
  21. /**
  22. * 测试连接
  23. * @return
  24. */
  25. func test1() {
  26. zkList := []string{"localhost:2181"}
  27. conn := getConnect(zkList)
  28. defer conn.Close()
  29. var flags int32 = 0
  30. //flags有4种取值:
  31. //0:永久,除非手动删除
  32. //zk.FlagEphemeral = 1:短暂,session断开则改节点也被删除
  33. //zk.FlagSequence = 2:会自动在节点后面添加序号
  34. //3:Ephemeral和Sequence,即,短暂且自动添加序号
  35. conn.Create("/go_servers", nil, flags, zk.WorldACL(zk.PermAll)) // zk.WorldACL(zk.PermAll)控制访问权限模式
  36. time.Sleep(20 * time.Second)
  37. }
  38. /*
  39. 删改与增不同在于其函数中的version参数,其中version是用于 CAS支持
  40. func (c *Conn) Set(path string, data []byte, version int32) (*Stat, error)
  41. func (c *Conn) Delete(path string, version int32) error
  42. demo:
  43. if err = conn.Delete(migrateLockPath, -1); err != nil {
  44. log.Error("conn.Delete(\"%s\") error(%v)", migrateLockPath, err)
  45. }
  46. */
  47. /**
  48. * 测试临时节点
  49. * @return {[type]}
  50. */
  51. func test2() {
  52. zkList := []string{"localhost:2181"}
  53. conn := getConnect(zkList)
  54. defer conn.Close()
  55. conn.Create("/testadaadsasdsaw", nil, zk.FlagEphemeral, zk.WorldACL(zk.PermAll))
  56. time.Sleep(20 * time.Second)
  57. }
  58. /**
  59. * 获取所有节点
  60. */
  61. func test3() {
  62. zkList := []string{"localhost:2181"}
  63. conn := getConnect(zkList)
  64. defer conn.Close()
  65. children, _, err := conn.Children("/go_servers")
  66. if err != nil {
  67. fmt.Println(err)
  68. }
  69. fmt.Printf("%v \n", children)
  70. }
  71. func main() {
  72. test3()
  73. }