这里的创建zk客户端采用的是一个叫Curator的工具包,建议后面可以研究下,并将这个工具包封装为自己的

    1. public CuratorZookeeperClient(URL url) {
    2. super(url);
    3. try {
    4. int timeout = url.getParameter(Constants.TIMEOUT_KEY, 5000);
    5. CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder()
    6. .connectString(url.getBackupAddress())
    7. .retryPolicy(new RetryNTimes(1, 1000))
    8. .connectionTimeoutMs(timeout);
    9. String authority = url.getAuthority();
    10. if (authority != null && authority.length() > 0) {
    11. builder = builder.authorization("digest", authority.getBytes());
    12. }
    13. client = builder.build();
    14. client.getConnectionStateListenable().addListener(new ConnectionStateListener() {
    15. @Override
    16. public void stateChanged(CuratorFramework client, ConnectionState state) {
    17. if (state == ConnectionState.LOST) {
    18. CuratorZookeeperClient.this.stateChanged(StateListener.DISCONNECTED);
    19. } else if (state == ConnectionState.CONNECTED) {
    20. CuratorZookeeperClient.this.stateChanged(StateListener.CONNECTED);
    21. } else if (state == ConnectionState.RECONNECTED) {
    22. CuratorZookeeperClient.this.stateChanged(StateListener.RECONNECTED);
    23. }
    24. }
    25. });
    26. client.start();
    27. } catch (Exception e) {
    28. throw new IllegalStateException(e.getMessage(), e);
    29. }
    30. }