二:zookeeper客户度连接

问题1:

  JAVA的API的Server和linux上跑的有zkServer有什么区别呢?

我的猜想:

  JAVA上跑的只是一种修改Linux上跑的zookeeper的内容的方式,JAVA的API写的Zookeeper的Server只是应用在服务器上用来改数据信息的。而zkServer跑的则是实实在在的在搭建集群环境。

 

1.客户端连接中可能遇到的问题。

  

一:KeeperErrorCode = ConnectionLoss for /

  请看以下博客(我是第四个错误,所以我的代码修改了等待连接的功能)

  https://blog.csdn.net/weixin_41673769/article/details/89385797

 

 

2.小技巧:eclipse返回值快捷键

  光标放到调用方法分号 ' ; ' 后面 ,使用Ctrl+1,直接回车,

 

例子:

package day_one;

import java.awt.List;
import java.io.IOException;
import java.util.Iterator;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.ZooKeeper.States;
import org.apache.zookeeper.data.Stat;

public class TestZk {
    private static final String CONN_STRING = "192.168.204.128:2181,192.168.204.129:2181,192.168.204.130:2181";
    private static final int sessionTimeOut = 2000;
    ZooKeeper zkClient = null;
    // 1 。连接客户端
    // 2. 写入注册信息

    public void connect_client() throws Exception {
        // 客户端连接
        zkClient = new ZooKeeper(CONN_STRING, sessionTimeOut, new Watcher() {
            @Override
            public void process(WatchedEvent event) {
                // TODO Auto-generated method stub
                // 收到事件通知后的回调函数
                System.out.println(event.getType()+"----"+event.getPath());
                try {
                    zkClient.getChildren("/", true);  //因为一次监听只能生效一次,所以要一直监听的话就需要,在事件调用的方法里面重新建立
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } 
            }
        });
        while (true) {
            /*此处的while 是因为,如果还没有连接好就创建目录的话,就会发生错误*/
            if (States.CONNECTING==zkClient.getState()) {
                System.out.println("i whell sleep");
                Thread.sleep(1000);
            }else {
                break;
            }
        }
        /**
         * 数据的增删改查
         * */
        // 参数1:要创建的节点路径 参数2:节点数据要转换成 bytes类型  参数3:节点的ACL(访问控制列表)权限  参数4:节点的类型
        String nodeCreat =  zkClient.create("/eclipse_4", "hello_zk".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        // 上传的数据可以是任何一种,只要转成bytes就可以    
        
        // 查子节点
        
        java.util.List<String> children =  zkClient.getChildren("/", true);//  "/" 是路径, true是选择是否生成监听        监听器只生效一次,生效就会调用process
        for (String childreString : children) {
            System.out.println(childreString);
        }
        
        //判断是否存在
        
        Stat exists = zkClient.exists("/a", false);
        
        //获取znode的数据
        byte[] data = zkClient.getData("/a", false, null);
    }
    public static void main(String[] args) throws Exception {
        TestZk testZk = new TestZk();
        testZk.connect_client();
        Thread.sleep(Long.MAX_VALUE);
    }
}
zookeeper样例代码

 

 

zookeeper 客户端与服务器代码

package day_one;

import java.io.IOException;
import java.util.List;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.ZooKeeper.States;

public class DistributedServer {
    private static final String CONN_STRING = "192.168.204.128:2181,192.168.204.129:2181,192.168.204.130:2181";
    private static final int sessionTimeOut = 2000;
    public static final String parenNoteString = "/Servers";
    private ZooKeeper zk = null;
    
    public void getConnect() throws Exception {
        zk=new ZooKeeper(CONN_STRING, sessionTimeOut, new Watcher() {
            
            @Override
            public void process(WatchedEvent event) {
                // TODO Auto-generated method stub
                System.out.println(event.getType()+"----"+event.getPath());
                try {
                    zk.getChildren("/", true);  //因为一次监听只能生效一次,所以要一直监听的话就需要,在事件调用的方法里面重新建立
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } 
            }
        });
        while (true) {
            /*此处的while 是因为,如果还没有连接好就创建目录的话,就会发生错误*/
            if (States.CONNECTING==zk.getState()) {
                System.out.println("connect...");
                Thread.sleep(1000);
            }else {
                
                break;
            }
        }
    }
    
    public void registerServer(String hostname) throws Exception, Exception {
        if (zk.exists(parenNoteString, false) != null){
            String create = zk.create(parenNoteString+"/server", hostname.getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
            System.out.println(hostname+" Server is logging");
        }else {
            zk.create(parenNoteString, null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            String create = zk.create(parenNoteString+"/server", hostname.getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
            
            System.out.println("no "+parenNoteString+" please add node");
        }
        
        
    }

    public void getChild() throws Exception, InterruptedException {
        List<String> getChildList = zk.getChildren("/", false);
        for (String child : getChildList) {
            System.out.println(child);
        }
    }
    
    public static void main(String[] args) throws Exception {
    /*
     * 1.获取zk连接
     * 2.利用zk连接注册服务器信息
     * 3.启动业务功能
     * */
        
        DistributedServer server = new DistributedServer();
        server.getConnect();
        server.getChild();
        server.registerServer(args[0]);
        Thread.sleep(Long.MAX_VALUE);
}
}
服务器
package day_one;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.ZooKeeper.States;

public class DistributedClient {
    private static final String CONN_STRING = "192.168.204.128:2181,192.168.204.129:2181,192.168.204.130:2181";
    private static final int sessionTimeOut = 2000;
    public static final String parenNoteString = "/Servers";
    private volatile ArrayList<String> allServerlist;
    private ZooKeeper zk = null;
    
    public void clientConnect() throws Exception {
        zk = new ZooKeeper(CONN_STRING, sessionTimeOut, new Watcher() {
            
            @Override
            public void process(WatchedEvent event) {
                // TODO Auto-generated method stub
                try {
                    getServer();
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });
        
        while (true) {
            /*此处的while 是因为,如果还没有连接好就创建目录的话,就会发生错误*/
            if (States.CONNECTING==zk.getState()) {
                System.out.println("connect...");
                Thread.sleep(1000);
            }else {
                
                break;
            }
        }
        
    }
    
    public void getServer() throws Exception, Exception {
        List<String> children = zk.getChildren(parenNoteString, true);
        
        ArrayList<String> nodeDatArrayList = new ArrayList<String>();
        for (String childrenString : children) {
            byte[] data = zk.getData(parenNoteString+"/"+childrenString, false, null);
            nodeDatArrayList.add(new String(data));
        }
        allServerlist = nodeDatArrayList;
        System.out.println(allServerlist);
    }
    public static void main(String[] args) throws Exception {
    /*
     * 1.连接Zookeeper
     * 2.获取Server信息
     *         如果有变化就重新获取(watch)
     * 3.业务功能
     * 
     * */
    DistributedClient distributedClient = new DistributedClient();
    distributedClient.clientConnect();
    distributedClient.getServer();
    }
}
客户端

 

posted @ 2020-11-30 21:34  晴晴小可爱的小弟  阅读(103)  评论(0编辑  收藏  举报