zookeeper系列(四)—客户端API使用

zookeeper系列(四)—客户端API使用

前言

大家好,牧码心今天给大家推荐一篇zookeeper系列(四)—客户端API使用的文章,在实际工作中有很多应用场景,希望对你有所帮助。内容如下:

  • 概要
  • 创建和关闭会话
  • 创建和查看节点
  • 修改和删除节点
  • 设置权限
  • curator框架

概要

zookeeper提供了zkCli.sh脚本,通过命令交互方式调试zk集群,但在项目开发中不推荐使用。zookeeper官方提供了java和C中语言的客户端,实际开发时我们一般会使用相应的zookeeper API,或者使用封装更高级的框架库 Curator。
本文java客户端为例来实现创建会话,创建节点,监听节点,删除节点,获取数据,设置权限,关闭会话等功能。

依赖

在使用zookeeper API之前,我们需要引入相关API的依赖,依赖方式如下,这里以maven为例:

<dependency>
            <groupId>org.apache.zookeeper</groupId>
            <artifactId>zookeeper</artifactId>
            <version>3.5.5</version>
</dependency>

这里选择的版本是3.5.5,更多版本选择,详见:https://mvnrepository.com/artifact/org.apache.zookeeper/zookeeper

创建和关闭会话

  • 创建会话
    启动zookeeper服务端后,客户端可通过构造函数 ZooKeeper()创建会话,实例化后将会自动与集群建立连接。函数定义如下:
ZooKeeper(String connectionString, int sessionTimeout, Watcher watcher)

函数参数说明如下:

参数名称类型说明
connectStringString连接串,包括ip+端口 ,集群模式下用逗号隔开 hadoop01:2181,hadoop02:2181,hadoop03:2181
sessionTimeoutint会话超时时间,该值不能超过服务端所设置的 minSessionTimeout 和maxSessionTimeout
watcherWatcher会话监听器,服务端事件将会触该监听

示例代码:

private ZooKeeper zooKeeper;
final CountDownLatch connectedSignal = new CountDownLatch(1);
public ZooKeeper connect(String host) throws IOException,InterruptedException {
      zooKeeper= new ZooKeeper(host,5000,new Watcher() {
      // 定义监听事件
         public void process(WatchedEvent we) {
            if (we.getState() == KeeperState.SyncConnected) {
               connectedSignal.countDown();
            }
         }
      });
      connectedSignal.await();
      return zooKeeper;
   }
  • 关闭会话
    关闭会话比较简单,zookeeper提供了close()函数来关闭会话,示例代码在此省略

创建和查看节点

  • 创建节点
    zookeeper提供了create()函数来创建新节点,函数定义如下:
String create(final String path, byte data[], List<ACL> acl,CreateMode createMode)

具体参数说明如下:

参数名称类型说明
pathString节点路径,如/myApp、/myApp/data
databyte[]节点赋值
aclList节点访问权限,zookeeper提供了一个接口定义权限,如ZooDefs.Ids下的属性
createModeCreateMode创建的节点类型,是一个枚举类 CreateMode

示例代码:

public void createData() throws KeeperException, InterruptedException {
       List<ACL> list = new ArrayList<>();
       int perm = ZooDefs.Perms.ADMIN | ZooDefs.Perms.READ;//cdwra
       ACL acl = new ACL(perm, new Id("world", "anyone"));
       ACL acl2= new ACL(perm, new Id("ip", "127.0.0.1"));
       list.add(acl);
       list.add(acl2);
       zooKeeper.create("/myApp/data", "hello".getBytes(), list, CreateMode.PERSISTENT);
   }
  • 查看节点
    zookeeper提供了getData()可查看节点和数据,函数定义如下:
getData(String path, Watcher watcher, Stat stat)

函数参数说明如下:

参数名称类型说明
pathString节点路径,如/myApp、/myApp/data
watchWatcher会话监听器,服务端事件将会触该监听
statStat节点元数据

示例代码:

public void getData() throws KeeperException, InterruptedException {
        Stat stat = new Stat();
        zooKeeper.getData("/myApp/data", new Watcher() {
            @Override
            public void process(WatchedEvent event) {
                try {
                    zooKeeper.getData(event.getPath(), this, null);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                System.out.println(event.getPath());
            }
        }, stat);
        System.out.println(stat);
        Thread.sleep(Long.MAX_VALUE);
    }
  • 查看子节点
    zookeeper提供了getChildren()获取子节点,函数定义如下:
List<String> getChildren(final String path, Watcher watcher)

函数参数说明如下:

参数名称类型说明
pathString节点路径,如/myApp、/myApp/data
watcherWatcher会话监听器,服务端事件将会触该监听,如boolean watcher 是true,则会使用

示例代码:

 public void getChild() throws KeeperException, InterruptedException {
        List<String> children = zooKeeper.getChildren("/myApp", event -> {
            System.out.println(event.getPath());
            try {
                zooKeeper.getChildren(event.getPath(), false);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        children.stream().forEach(System.out::println);
        Thread.sleep(Long.MAX_VALUE);
    }

修改和删除节点

  • 修改节点
    zookeeper提供了setData()函数来设置节点权限,函数定义如下:
setData(String path, byte[] data, int version)

函数参数说明如下:

参数名称类型说明
pathString节点路径,如/myApp、/myApp/data
databyte[]节点修改的数据
versionint节点当前的版本号

示例代码

public  void updateTest() throws
      KeeperException,InterruptedException {
      String path= "/myApp";
      byte[] data = "Success".getBytes(); 
      zookeeper.setData(path, data, zookeeper.exists(path,true).getVersion());
   }
  • 删除节点
    zookeeper提供了setData()函数来设置节点权限,函数定义如下:
delete(String path, int version)

函数参数说明如下:

参数名称类型说明
pathString节点路径,如/myApp、/myApp/data
versionint节点当前的版本号

示例代码

public  void deleteTest() throws
      KeeperException,InterruptedException {
      String path= "/myApp";
      zookeeper.delete(path, zookeeper.exists(path,true).getVersion());
   }

设置权限

zookeeper提供了setAcl()函数来设置节点权限,ACL权限结构为scheme🆔permission,具体的可参考中zookeeper系列(三)—节点详解的ACL的说明,函数定义如下:

setACL(final String path, List<ACL> acl, int aclVersion)

函数参数说明如下:

参数名称类型说明
pathString节点路径,如/myApp、/myApp/data
aclList节点访问权限,zookeeper提供了一个接口定义权限,如ZooDefs.Ids下的属性
aclVersionint节点权限版本号

示例代码:

public void setAclTest() throws KeeperException, InterruptedException {
        List<ACL> aclList = new ArrayList<>();
        int perm = ZooDefs.Perms.ADMIN | ZooDefs.Perms.READ|ZooDefs.Perms.WRITE;
        aclList.add(new ACL(perm, new Id("world", "anyone")));
        aclList.add(new ACL(ZooDefs.Perms.ALL, new Id("ip", "127.0.0.1")));
        zooKeeper.setACL("/myApp", aclList, 5);
    }

Curator框架

Curator是Netflix公司开源的一套zookeeper客户端框架,解决了很多Zookeeper客户端非常底层的细节开发工作,包括连接重连、反复注册Watcher和NodeExistsException异常等。Curator包含了几个包:

1、curator-framework:对zookeeper的底层api的一些封装;
2、curator-client:提供一些客户端的操作,例如重试策略等;
3、curator-recipes:封装了一些高级特性,如:Cache事件监听、选举、分布式锁、分布式计数器、分布式Barrier等

Maven依赖(使用curator的版本:4.3.0,对应Zookeeper的版本为:3.5.x,如果跨版本会有兼容性问题,很有可能导致节点操作失败):依赖方式见:https://mvnrepository.com/artifact/org.apache.curator/curator-client/4.3.0

  • 关于Curator框架使用可参考:http://curator.apache.org/getting-started.html

参考

  • https://www.tutorialspoint.com/zookeeper/zookeeper_api.htm
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值