zk - zookeeper实现配置中心

282 阅读1分钟

世界上并没有完美的程序,但是我们并不因此而沮丧,因为写程序就是一个不断追求完美的过程。

使用zk实现配置中心,只要抓住两点:

  1. znode存储配置信息
  2. watch监听配置信息的变化

下面是实现过程:

public class ConfigCenter {

    @Test
    public void test() {
        put();
        get();
    }

    /**
     * 配置信息的上传
     */
    private void put() {
        try {
            String path = "/application.yml";
            File file = new File(this.getClass().getResource(path).getFile());
            FileInputStream in = new FileInputStream(file);
            byte[] bytes = new byte[in.available()];
            in.read(bytes);
            in.close();

            String connect = "127.0.0.1:2181";
            ZkClient client = new ZkClient(connect);
            client.setZkSerializer(new BytesPushThroughSerializer());
            String configPath = "/config1";
            if (client.exists(configPath)) {
                client.writeData(configPath, bytes);
            } else {
                client.createPersistent(configPath, bytes);
            }
            client.close();
        } catch (Exception e) {e.printStackTrace();}
    }

    /**
     * 配置信息的获取
     */
    public void get() {
        String connect = "127.0.0.1:2181";
        ZkClient client = new ZkClient(connect);
        client.setZkSerializer(new BytesPushThroughSerializer());
        String configPath = "/config1";
        // 启动时首先读取配置信息
        byte[] bs = client.readData(configPath);
        System.out.println("config data : " +  new String(bs));
      // 监听配置信息的变化  
      client.subscribeDataChanges(configPath, new IZkDataListener() {
            @Override
            public void handleDataChange(String s, Object o) throws Exception {
                System.out.println("data change path : " + s);
                System.out.println("data change : " + new String((byte[]) o));
            }

            @Override
            public void handleDataDeleted(String s) throws Exception {
                System.out.println("data delete path : " + s);
            }
        });

        try {
            Thread.sleep(30000);
        } catch (Exception e) {e.printStackTrace();}
    }
}

如上,每个配置文件对应一个znode,就可以实现配置的集中处理,即配置中心。
当然如果实际使用还需要进行配置信息的解析或者写入等操作,在spring cloud中获取实时修改的配置信息,需要@RefreshScope注解的配合。当然也可以自己刷新配置,如通过applicationContext.refresh()。后续需要自己根据实际情况来实现了。

在这里插入图片描述