zookeeper应用场景

# zk ![image.png](https://cos.easydoc.net/48081513/files/kf572xps.png) ## 数据的发布订阅(配置中心) ![image.png](https://cos.easydoc.net/48081513/files/kgfzlqot.png) ## 将单个配置放到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); } } } ``` ## 分布式锁 > 1 ![image.png](https://cos.easydoc.net/31477061/files/ki3z30q1.png) >2 ![image.png](https://cos.easydoc.net/31477061/files/ki3ze5mj.png)