分享

zookeeper应用开发

由于zookeeper的client只有zookeeper一个对象,使用也比较简单,所以就不许要文字说明了,在代码中注释下就ok 了。
1.如何测试zookeeper的main方法。
2.zookeeper有哪些封装接口?
3.如何实现封装接口?
4.创建接口、销毁接口、写入接口、zookeeper修改及查询接口是什么?
5.如何创建sever1的连接client1 ?
6.如何创建一个针对server1的临时节点?






1、测试用的main方法

  1. package ClientExample;
  2. public class TestMain {
  3. public static void main(String[] args) {  
  4.         /*
  5.          * 测试流程
  6.          * 1、创建sever1的连接client1,并且创建一个永久性的/test节点
  7.          * 2、创建一个针对server1的临时节点
  8.          * 3、创建server2的连接client21,并创建一个针对server2的临时节点
  9.          * 4、创建server3的连接client3,并创建一个针对server3的临时节点
  10.          * 5、分别查看client1、client2、client3的三个节点的字节点数量,确定是否同步成功
  11.          * 6、修改client1的临时节点内容,然后在在client2和client3中查看
  12.          * 7、kill掉client3的线程,然后检查是watcher是否有通知给client1和client2
  13.          */  
  14.          
  15.          Thread t1= new ClientThread("127.0.0.1:2181","server1",false);  
  16.          Thread t2= new ClientThread("127.0.0.1:2182","server2",false);  
  17.          Thread t3= new ClientThread("127.0.0.1:2183","server3",false);  
  18.          Thread t4= new ClientThread("127.0.0.1:2181","server4",false);  
  19.            
  20.          t1.start();  
  21.          t2.start();  
  22.          t3.start();  
  23.          t4.start();  
  24.          ControlThread c = new ControlThread(t1, t2, t3, t4);  
  25.          c.start();  
  26.          int i=0;  
  27.          while(true)  
  28.          {  
  29.             i++;  
  30.             i--;  
  31.                
  32.          }  
  33.            
  34.          /*
  35.           * 测试控制台输出:
  36.           * connectIP:server4,path:null,state:SyncConnected,type:None
  37.           * connectIP:server3,path:/test,state:SyncConnected,type:NodeChildrenChanged
  38.           * connectIP:server4,path:/test/server4,state:SyncConnected,type:NodeCreated
  39.           * 。。。。。。。。。。。
  40.           *  
  41.           * connectIP:server2,path:null,state:Disconnected,type:None
  42.             server2exception,KeeperErrorCode = ConnectionLoss for /test
  43.             connectIP:newServer1,path:null,state:SyncConnected,type:None
  44.             connectIP:server1,path:/test,state:SyncConnected,type:NodeChildrenChanged
  45.             connectIP:server4,path:/test/server2,state:SyncConnected,type:NodeDeleted
  46.             connectIP:server4,path:/test,state:SyncConnected,type:NodeChildrenChanged
  47.             connectIP:newServer1,path:/test,state:SyncConnected,type:NodeChildrenChanged
  48.             connectIP:server3,path:/test/server2,state:SyncConnected,type:NodeDeleted
  49.             connectIP:server3,path:/test,state:SyncConnected,type:NodeChildrenChanged
  50.           */  
  51.     }  
  52. }
复制代码

2、zookeeper封装的接口:

  1. package ClientExample;
  2. import java.io.IOException;  
  3. import java.util.List;  
  4. import org.apache.zookeeper.KeeperException;  
  5. /**
  6. * zookeeper的操作封装接口,实现了常用的操作
  7. * 创建、销毁、写入、修改、查询等。
  8. * @author ransom
  9. *
  10. */  
  11. public interface ServerOperation {  
  12.     void init(String address,String serverName) throws IOException;  
  13.     void destroy() throws InterruptedException;  
  14.     List<String> getChilds(String path) throws KeeperException,  
  15.             InterruptedException;  
  16.     String getData(String path) throws KeeperException, InterruptedException;  
  17.     void changeData(String path, String data) throws KeeperException,  
  18.             InterruptedException;  
  19.     void delData(String path) throws KeeperException, InterruptedException;  
  20.     void apendTempNode(String path, String data) throws KeeperException,  
  21.             InterruptedException;  
  22.     void apendPresistentNode(String path, String data) throws KeeperException,  
  23.     InterruptedException;  
  24.       
  25.     void delNode(String path) throws KeeperException, InterruptedException;  
  26.     boolean exist(String path) throws KeeperException, InterruptedException;  
  27. }
复制代码

3、接口的实现:

  1. package ClientExample;
  2. import java.io.IOException;  
  3. import java.util.List;  
  4. import org.apache.zookeeper.CreateMode;  
  5. import org.apache.zookeeper.KeeperException;  
  6. import org.apache.zookeeper.ZooKeeper;  
  7. import org.apache.zookeeper.ZooDefs.Ids;  
  8. public class ServerConnector implements ServerOperation {  
  9.     // 创建一个Zookeeper实例,第一个参数为目标服务器地址和端口,第二个参数为Session超时时间,第三个为节点变化时的回调方法  
  10.     private ZooKeeper zk = null;  
  11.     public void init(String address,String serverName) throws IOException {  
  12.         zk = new ZooKeeper(address, 500000,  
  13.                 new MultiWatcher(serverName));
  14.     }  
  15.     @Override  
  16.     public void destroy() throws InterruptedException {  
  17.         // TODO Auto-generated method stub  
  18.         if (zk != null) {  
  19.             zk.close();  
  20.         }  
  21.     }  
  22.     @Override  
  23.     public List<String> getChilds(String path) throws KeeperException, InterruptedException {  
  24.         // TODO Auto-generated method stub  
  25.         if (zk != null) {  
  26.             return zk.getChildren(path, true);  
  27.         }  
  28.         return null;  
  29.     }  
  30.     @Override  
  31.     public String getData(String path) throws KeeperException, InterruptedException {  
  32.         // TODO Auto-generated method stub  
  33.         if (zk != null) {  
  34.             // 取得/root/childone节点下的数据,返回byte[]  
  35.             byte[] b = zk.getData(path, true, null);  
  36.             return new String(b);  
  37.         }  
  38.         return null;  
  39.     }  
  40.     @Override  
  41.     public void changeData(String path,String data) throws KeeperException, InterruptedException {  
  42.         // TODO Auto-generated method stub  
  43.         if (zk != null) {  
  44.             // 修改节点/root/childone下的数据,第三个参数为版本,如果是-1,那会无视被修改的数据版本,直接改掉  
  45.             zk.setData(path, data.getBytes(),-1);  
  46.         }  
  47.     }  
  48.     @Override  
  49.     public void delData(String path) throws InterruptedException, KeeperException {  
  50.         // TODO Auto-generated method stub  
  51.         if (zk != null) {  
  52.             // 删除/root/childone这个节点,第二个参数为版本,-1的话直接删除,无视版本  
  53.             zk.delete(path, -1);  
  54.         }  
  55.     }  
  56.     @Override  
  57.     public void delNode(String path) throws InterruptedException, KeeperException {  
  58.         // TODO Auto-generated method stub  
  59.         if (zk != null) {  
  60.             zk.delete(path, -1);  
  61.         }  
  62.     }  
  63.     @Override  
  64.     public boolean exist(String path) throws KeeperException,  
  65.             InterruptedException {  
  66.         // TODO Auto-generated method stub  
  67.         if (zk != null) {  
  68.             return zk.exists(path, true)!=null;  
  69.         }  
  70.         return false;  
  71.     }  
  72.     @Override  
  73.     public void apendTempNode(String path, String data) throws KeeperException,  
  74.             InterruptedException {  
  75.         // TODO Auto-generated method stub  
  76.         // TODO Auto-generated method stub  
  77.         if (zk != null)   
  78.         {  
  79.             // 创建一个节点root,数据是mydata,不进行ACL权限控制,节点为永久性的(即客户端shutdown了也不会消失)  
  80.             /*
  81.              * 创建一个给定的目录节点 path, 并给它设置数据,
  82.              * CreateMode 标识有四种形式的目录节点,分别是  
  83.              * PERSISTENT:持久化目录节点,这个目录节点存储的数据不会丢失;
  84.              * PERSISTENT_SEQUENTIAL:顺序自动编号的目录节点,这种目录节点会根据当前已近存在的节点数自动加 1,然后返回给客户端已经成功创建的目录节点名;
  85.              * EPHEMERAL:临时目录节点,一旦创建这个节点的客户端与服务器端口也就是 session 超时,这种节点会被自动删除;
  86.              * EPHEMERAL_SEQUENTIAL:临时自动编号节点  
  87.              */  
  88.             zk.create(path, data.getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);  
  89.         }  
  90.     }  
  91.     @Override  
  92.     public void apendPresistentNode(String path, String data)  
  93.             throws KeeperException, InterruptedException {  
  94.         // TODO Auto-generated method stub  
  95.         if (zk != null)   
  96.         {  
  97.             // 创建一个节点root,数据是mydata,不进行ACL权限控制,节点为永久性的(即客户端shutdown了也不会消失)  
  98.             /*
  99.              * 创建一个给定的目录节点 path, 并给它设置数据,
  100.              * CreateMode 标识有四种形式的目录节点,分别是  
  101.              * PERSISTENT:持久化目录节点,这个目录节点存储的数据不会丢失;
  102.              * PERSISTENT_SEQUENTIAL:顺序自动编号的目录节点,这种目录节点会根据当前已近存在的节点数自动加 1,然后返回给客户端已经成功创建的目录节点名;
  103.              * EPHEMERAL:临时目录节点,一旦创建这个节点的客户端与服务器端口也就是 session 超时,这种节点会被自动删除;
  104.              * EPHEMERAL_SEQUENTIAL:临时自动编号节点  
  105.              */  
  106.             zk.create(path, data.getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);  
  107.         }  
  108.     }  
  109. }  
复制代码


4、一个控制的线程,主要用来强制kill掉连接的线程
  1. package ClientExample;
  2. public class ControlThread extends Thread{  
  3.     public ControlThread(Thread t1,Thread t2,Thread t3,Thread t4)  
  4.     {  
  5.         list[0]=t1;  
  6.         list[1]=t2;  
  7.         list[2]=t4;  
  8.         list[3]=t4;  
  9.     }  
  10.       
  11.     private Thread[] list = new Thread[4];  
  12.     private int num=0;  
  13.     public void run()  
  14.     {  
  15.         while(true)  
  16.         {  
  17.             if(num==7)  
  18.             {  
  19.                 list[2].stop();  
  20.                 System.out.println("kill server3");  
  21.             }  
  22.             if(num==15)  
  23.             {  
  24.                 list[3].stop();  
  25.                 System.out.println("kill server4");  
  26.             }  
  27.             try {  
  28.                 sleep(1000);  
  29.             } catch (InterruptedException e) {  
  30.                 // TODO Auto-generated catch block  
  31.                 e.printStackTrace();  
  32.             }  
  33.         }  
  34.     }  
  35. }  
复制代码

5、watcher 的实现:

  1. package ClientExample;
  2. import org.apache.zookeeper.WatchedEvent;  
  3. import org.apache.zookeeper.Watcher;  
  4. import org.apache.zookeeper.Watcher.Event.EventType;  
  5. import org.apache.zookeeper.Watcher.Event.KeeperState;  
  6. /**
  7. * 提供给多个client使用的watcher
  8. * @author ransom
  9. *
  10. */  
  11. public class MultiWatcher implements Watcher{  
  12.     public MultiWatcher(String address)  
  13.     {  
  14.         connectAddress=address;  
  15.     }  
  16.       
  17.     private String connectAddress=null;  
  18.       
  19.     @Override  
  20.     public void process(WatchedEvent event) {  
  21.         // TODO Auto-generated method stub  
  22.         String outputStr="";  
  23.         if(connectAddress!=null){  
  24.             outputStr+="connectIP:"+connectAddress;  
  25.         }  
  26.         outputStr+=",path:"+event.getPath();  
  27.         outputStr+=",state:"+event.getState();  
  28.         outputStr+=",type:"+event.getType();  
  29.          
  30.         System.out.println(outputStr);  
  31.     }  
  32. }  
复制代码



6、client 运行 的Thread

  1. package ClientExample;
  2. import java.io.IOException;  
  3. import java.text.DateFormat;  
  4. import java.text.SimpleDateFormat;  
  5. import java.util.Date;  
  6. import java.util.List;  
  7. import org.apache.zookeeper.KeeperException;  
  8. public class ClientThread extends Thread{  
  9.     public ClientThread(String address,String serverName,boolean islog)  
  10.     {  
  11.         this.address=address;  
  12.         this.serverName=serverName;  
  13.         try {  
  14.             otherOperation();  
  15.         } catch (KeeperException e) {  
  16.             // TODO Auto-generated catch block  
  17.             e.printStackTrace();  
  18.         } catch (InterruptedException e) {  
  19.             // TODO Auto-generated catch block  
  20.             e.printStackTrace();  
  21.         }  
  22.         this.islog=islog;  
  23.     }  
  24.     private boolean islog=true;  
  25.     private final String rootPath = "/test";  
  26.     private String address;  
  27.     private String serverName;  
  28.     private ServerOperation operationCient = null;  
  29.       
  30.     public void run()  
  31.     {  
  32.         if(operationCient==null)  
  33.         {  
  34.             System.out.println("operationCient=null");  
  35.             return;  
  36.         }  
  37.          
  38.         while(true){  
  39.             try {  
  40.                 if(islog){  
  41.                     System.out.println(serverName+",loopTime:"+getNowTime());  
  42.                 }  
  43.                 observerChildData(rootPath);  
  44.             } catch (KeeperException e) {  
  45.                 // TODO Auto-generated catch block  
  46.                 System.out.println(serverName+"exception,"+e.getLocalizedMessage());  
  47.                 try {  
  48.                     operationCient= new ServerConnector();  
  49.                     operationCient.init("127.0.0.1:2181","newServer1");  
  50.                 } catch (IOException e1) {  
  51.                     // TODO Auto-generated catch block  
  52.                     System.out.println(serverName+" reconnect  exception,"+e.getLocalizedMessage());  
  53.                 }  
  54.             } catch (InterruptedException e) {  
  55.                 // TODO Auto-generated catch block  
  56.                 e.printStackTrace();  
  57.             }  
  58.             try {  
  59.                 sleep(2000);  
  60.             } catch (InterruptedException e) {  
  61.                 // TODO Auto-generated catch block  
  62.                 e.printStackTrace();  
  63.             }  
  64.         }  
  65.          
  66.     }  
  67.       
  68.     /*
  69.      * 测试流程
  70.      * 1、创建sever1的连接client1,并且创建一个永久性的/test节点
  71.      * 2、创建一个针对server1的临时节点
  72.      * 3、创建server2的连接client21,并创建一个针对server2的临时节点
  73.      * 4、创建server3的连接client3,并创建一个针对server3的临时节点
  74.      * 5、分别查看client1、client2、client3的三个节点的字节点数量,确定是否同步成功
  75.      * 6、修改client1的临时节点内容,然后在在client2和client3中查看
  76.      * 7、kill掉client3的线程,然后检查是watcher是否有通知给client1和client2
  77.      */  
  78.       
  79.       
  80.     private void otherOperation() throws KeeperException, InterruptedException  
  81.     {  
  82.         operationCient= new ServerConnector();  
  83.         try {  
  84.             operationCient.init(address,serverName);  
  85.         } catch (IOException e) {  
  86.             // TODO Auto-generated catch block  
  87.             e.printStackTrace();  
  88.         }  
  89.          
  90.         if(operationCient==null)  
  91.         {  
  92.             System.out.println("operationCient=null");  
  93.             return;  
  94.         }  
  95.         if(!operationCient.exist(rootPath))  
  96.         {  
  97.             operationCient.apendPresistentNode(rootPath, "this node is creat by " + serverName);  
  98.         }  
  99.          
  100.         //添加临时节点  
  101.         if(!operationCient.exist(rootPath+"/"+serverName))  
  102.         {  
  103.             operationCient.apendTempNode(rootPath+"/"+serverName,  "this node is creat by " + serverName);  
  104.         }  
  105.         observerChildData("/test");  
  106.          
  107.          
  108.          
  109.         //修改临时节点内容  
  110.         operationCient.changeData(rootPath+"/"+serverName, "this node is changed by " + serverName);  
  111.         //临时节点内容  
  112.         List<String> childs=operationCient.getChilds(rootPath);  
  113.         for(String str : childs)  
  114.         {  
  115.             System.out.println("observered by "+ serverName +": child node is :"+ str);  
  116.         }  
  117.          
  118.     }  
  119.       
  120.     //查看临时节点的同步状态  
  121.     public void observerChildData(String path) throws KeeperException, InterruptedException  
  122.     {  
  123.         if(operationCient==null)  
  124.         {  
  125.             System.out.println("operationCient=null");  
  126.             return;  
  127.         }  
  128.          
  129.         List<String> childs=operationCient.getChilds(rootPath);  
  130.         if(islog){  
  131.             System.out.println("observered by "+ serverName +": childs len is :"+ childs.size());  
  132.         }  
  133.         for(String str : childs)  
  134.         {  
  135.             if(islog){  
  136.                 System.out.println("observered by "+ serverName +": child node is :"+ str+",data is :"+operationCient.getData(rootPath+"/"+str));  
  137.             }  
  138.         }  
  139.          
  140.     }  
  141.     public String getNowTime()  
  142.     {  
  143.         DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");  
  144.         return format1.format(new Date());  
  145.     }  
  146.       
  147.       
  148. }  
复制代码





已有(2)人评论

跳转到指定楼层
小姜 发表于 2016-12-28 14:00:53
感谢楼主分享
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关闭

推荐上一条 /2 下一条