四:ZK客户端Curator

apache原生的zookeeper不太友好,如今市面上有两种,一种是zkclient,在一中就是apache的curator,node

相比于zkclient来讲,curator文档更友好,提供了Fluent风格的API,更加易懂易操做apache

首先是建立zk链接session

CuratorFramework client = builder.connectString("192.168.11.56:2180")  //ip:portui

       .sessionTimeoutMs(30000)  //session timeouotspa

       .connectionTimeoutMs(30000)   //connect timeout事务

      .canBeReadOnly(false)  ip

       .retryPolicy(new ExponentialBackoffRetry(1000, 3))  //重试策略文档

       .namespace(namespace)  //命名空间get

       .build();  it

if(!client.isStart())

    client.start();  

建立节点:

    if(client.checkExists().forPath(path) == null)

        client.create().forPath(path, value.toBytes);

建立节点的时候还有临时节点,临时有序节点,永久有序节点,采用withMode(CreateMode.),CreateMode提供了集中实现

若是不判断的话,在节点存在的时候会抛出NodeExistsException

判断节点是否存在

    Stat stat = client.checkExists().forPath(path);

    stat类里面包含了不少信息,包括version,zxid,等信息,zk里面每次更新都会更新一次版本,采用乐观锁的策略,zxid是事务的id(zk里面,事务id采用64位,前32位表示了leader的统治期,后32位表示了事务的序号)

更新数据

  if(client.checkExists().forPath(path) != null)

        client.setData().forPath(path, value.toBytes);

若是不判断的话,在节点存在的时候会抛出NodeExistsException

删除数据:

if(client.checkExists().forPath(path) != null)

        client.delete().forPath(path);

若是不判断的话,在节点存在的时候会抛出NoNodeException

获取子节点:

if(client.checkExists().forPath(path) != null)

       List<String> childList = client.getChildren().forPath(path);

若是不判断的话,在节点存在的时候会抛出NoNodeException

监听:

监听分为监听Node和Path,node有nodeUpdate和nodeDelete时间,PathChildrenCache有添加子节点,删除子节点等监听,此处再也不细说

其他Election,Lock,Automic等有兴趣的话能够去百度,不少

相关文章
相关标签/搜索