思路:
我们在开发的时候,有时候需要获取一些公共的配置,比如数据库连接信息等,并且偶然可能需要更新配置。如果我们的服务器有N多台的话,那修改起来会特别的麻烦,并且还需要重新启动。这里Zookeeper就可以很方便的实现类似的功能。
步骤
1.将公共的配置存放在Zookeeper的节点中
2应用程序可以连接到Zookeeper中并对Zookeeper中配置节点进行读取或者修改(对于写操作可以进行权限验证设置),下面是具体的流程图:
1.引入pom 文件
<dependency> <groupId>org.apache.zookeeper</groupId> <artifactId>zookeeper</artifactId> <version>3.4.8</version> </dependency> <dependency> <groupId>org.apache.curator</groupId> <artifactId>curator-framework</artifactId> <version>4.0.0</version> </dependency> <dependency> <groupId>org.apache.curator</groupId> <artifactId>curator-recipes</artifactId> <version>4.0.0</version> </dependency>
2.实际代码
package com.vince.xq.kafka; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.retry.ExponentialBackoffRetry; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.data.Stat; public class WatcherDemo implements Watcher { @Override public void process(WatchedEvent event) { System.out.println("eventType:" + event.getType()); if (event.getType() == Event.EventType.NodeDataChanged) { System.out.println(event.getPath()); CuratorFramework curatorFramework = CuratorFrameworkFactory. builder().connectString("127.0.0.1:2181"). sessionTimeoutMs(4000).retryPolicy(new ExponentialBackoffRetry(1000, 3)). namespace("").build(); curatorFramework.start(); Stat stat = new Stat(); //查询节点数据 byte[] bytes = new byte[0]; try { bytes = curatorFramework.getData().storingStatIn(stat).forPath("/watcher"); } catch (Exception e) { e.printStackTrace(); } System.out.println(new String(bytes)); curatorFramework.close(); } } }
package com.vince.xq.kafka; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.ZooDefs; import org.apache.zookeeper.ZooKeeper; import java.io.IOException; public class ZkTest { static ZooKeeper zooKeeper; static { try { zooKeeper = new ZooKeeper("127.0.0.1:2181", 4000, new WatcherDemo()); } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) throws KeeperException, InterruptedException { String path = "/watcher"; if (zooKeeper.exists(path, false) == null) { zooKeeper.create("/watcher", "0".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } Thread.sleep(1000); System.out.println("-----------"); while (true) { //true表示使用zookeeper实例中配置的watcher zooKeeper.exists(path, true); } } }
3.spring boot 集成 zk 实现配置中心
源码参考:
zhugezifang/zkconfig-springboot (github.com)