其他分享
首页 > 其他分享> > zookeeper CURD增删改查

zookeeper CURD增删改查

作者:互联网

 <dependency>
            <groupId>org.apache.zookeeper</groupId>
            <artifactId>zookeeper</artifactId>
            <version>3.6.0</version>
 </dependency>
package top.xiongmingcai.zookeeper;

import org.apache.zookeeper.*;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;

import java.io.IOException;

@FixMethodOrder(MethodSorters.NAME_ASCENDING) // 按方法名首字母顺序执行
public class CurdZkTest {
  private static final String SERVER_PATH = "127.0.0.1:2181";
  private static final int TIMEOUT = 5000;
  private static final String PATH = "/node_1";
  private static ZooKeeper zk;

  static {
    Watcher watcher =
        event -> {
          System.out.println("--> event : " + event);
        };
    try {
      zk = new ZooKeeper(SERVER_PATH, TIMEOUT, watcher);
    } catch (IOException e) {
      throw new RuntimeException("", e);
    }
  }

  @Test
  public void a_stat() {
    System.out.println("zk.getState() = " + zk.getState());
  }

  @Test
  public void b_createNode() throws KeeperException, InterruptedException {
    byte[] bytes = "hello world".getBytes();
    zk.create(PATH, bytes, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
  }

  @Test
  public void c_getNode() throws KeeperException, InterruptedException {
    byte[] data = zk.getData(PATH, null, null);
    System.out.println("设置的值 = " + new String(data));
  }

  @Test
  public void d_setNode() throws KeeperException, InterruptedException {
    zk.setData(PATH, "hello google".getBytes(), 0);
  }

  @Test
  public void e_getNode2() throws KeeperException, InterruptedException {
    byte[] data = zk.getData(PATH, null, null);
    System.out.println("改变后的值 = " + new String(data));
  }

  @Test
  public void f_delete2() throws KeeperException, InterruptedException {
    //zk.delete(PATH, 0);// 会抛异常因为版本相同
    zk.delete(PATH, 1);//version 要递增
  }
}

image

标签:zk,void,zookeeper,改查,CURD,Test,PATH,public
来源: https://www.cnblogs.com/xmc000/p/15211536.html