zookeeper入门概念
# zookeeper
## 概念 什么是zk 和应用
![image.png](https://cos.easydoc.net/48081513/files/kf53bv7l.png)
![image.png](https://cos.easydoc.net/48081513/files/kf53heie.png)
## 单机安装
![image.png](https://cos.easydoc.net/48081513/files/kf53klvk.png)
## 客户端操作
![image.png](https://cos.easydoc.net/48081513/files/kf53tveg.png)
### 创建abc 赋值888
![image.png](https://cos.easydoc.net/48081513/files/kf547g9x.png)
### 查看读取
![image.png](https://cos.easydoc.net/48081513/files/kf5496oi.png)
### 修改
![image.png](https://cos.easydoc.net/48081513/files/kf54b94g.png)
### 删除
![image.png](https://cos.easydoc.net/48081513/files/kf54chn4.png)
### quit 退出操作
## java使用原生zk
![image.png](https://cos.easydoc.net/48081513/files/kf54iaba.png)
![image.png](https://cos.easydoc.net/48081513/files/kf54gvgr.png)
## java客户端使用zk(建议使用)
![image.png](https://cos.easydoc.net/48081513/files/kf54m9gr.png)
> springboot pom.xml
```
<!-- https://mvnrepository.com/artifact/org.apache.zookeeper/zookeeper -->
<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
<version>3.4.13</version>
<type>pom</type>
</dependency>
<!-- https://mvnrepository.com/artifact/com.101tec/zkclient -->
<dependency>
<groupId>com.101tec</groupId>
<artifactId>zkclient</artifactId>
<version>0.11</version>
</dependency>
```
## 将单个配置放到zookeeper上
```
public static void main(String[] args) {
ZkClient client = new ZkClient("localhost:2181");
client.setZkSerializer(new MyZkSerializer());
String configPath = "/config1";
String value = "222222wtl";
if (client.exists(configPath)) { //节点是否存在
client.writeData(configPath, value); //写入数据
} else {
client.createPersistent(configPath, value); //创建持久节点 写入数据
}
client.close();
}
```
> 序列化 反序列化
```
public class MyZkSerializer implements ZkSerializer {
String charset = "UTF-8";
public Object deserialize(byte[] bytes) throws ZkMarshallingError {
try {
return new String(bytes, charset);
} catch (UnsupportedEncodingException e) {
throw new ZkMarshallingError(e);
}
}
public byte[] serialize(Object obj) throws ZkMarshallingError {
try {
return String.valueOf(obj).getBytes(charset);
} catch (UnsupportedEncodingException e) {
throw new ZkMarshallingError(e);
}
}
}
```