1.maven依赖
<!-- java语言连接zk -->
<dependency>
<groupId>com.101tec</groupId>
<artifactId>zkclient</artifactId>
<version>0.8</version>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.0.0.RELEASE</version>
</dependency>
2. 说明
ZK本质上类似于一个文件系统,根据url去创建对应的node,node全路径名称不允许重复。
3.ZK四种节点类型
有序持久 CreateMode.PERSISTENT_SEQUENTIAL
无序持久 CreateMode.PERSISTENT
有序临时 CreateMode.EPHEMERAL_SEQUENTIAL
无序临时 CreateMode.EPHEMERAL
4.ZK支持ACL权限控制
ACL权限模型,实际上就是对每个节点实现控制
身份的认证有4种方式:
world:默认方式,相当于全世界都能访问
auth:代表已经认证通过的用户(cli中可以通过addauth digest user:pwd 来添加当前上下文中的授权用户)
digest:即用户名:密码这种方式认证,这也是业务系统中最常用的
ip:使用Ip地址认证
5.入门案例
建立连接,创建文件节点
package live.yanxiaohui.test;
import org.I0Itec.zkclient.ZkClient;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import java.util.concurrent.CountDownLatch;
/**
* @Description todo
* @Author: yanxh<br>
* @Date 2020-04-29 16:22<br>
* @Version 1.0<br>
*/
public class Test1 {
// zk服务器的ip和端口
public static final String addr = "127.0.0.1:2181";
// 参数2 zk超时时间
private static final int TIMEOUT = 5000;
// 计数器
private static CountDownLatch countDownLatch = new CountDownLatch(1);
public static void main(String[] args) throws Exception{
ZooKeeper zooKeeper = new ZooKeeper(addr, TIMEOUT, (watchedEvent) -> {
Watcher.Event.KeeperState state = watchedEvent.getState();
if (state == Watcher.Event.KeeperState.SyncConnected) {
System.out.println("zk连接成功");
// 计数器减去1
countDownLatch.countDown();
}
});
// 计数器结果必须是为0的情况才继续执行
System.out.println("zk正在连接等待...");
countDownLatch.await();
System.out.println("开始创建我们的节点");
// 创建节点
/**
* 参数1 路径名称
* 参数2 节点value
* 参数3 节点权限acl
* 参数4 节点类型
*/
String s = zooKeeper.create("/zkDemo/study", "zhis is a demo".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,
CreateMode.PERSISTENT);
System.out.println(s);
zooKeeper.close();
}
}
zk连接账号获取数据
// 1.创建zooKeeper连接
ZooKeeper zooKeeper = new ZooKeeper("127.0.0.1", 500, (watchedEvent)->System.out.println(watchedEvent.getState().name()));
// 2.设置zk连接账号
zooKeeper.addAuthInfo("digest", "guest:guest123".getBytes());
byte[] bytes = zooKeeper.getData("/zkDemo", null, new Stat());
String string = new String(bytes);
System.out.println(string);
欢迎大家和帝都的雁积极互动,头脑交流会比个人埋头苦学更有效!共勉!
公众号:帝都的雁