Java实现与ZooKeeper的连接

时间:2021-04-29 08:27:12

Java实现

新建一个类实现接口Watcher. 是指:

This interface specifies the public interface an event handler class must implement. A ZooKeeper client will get various events from the ZooKeepr server it connects to. An application using such a client handles these events by registering a callback object with the client. The callback object is expected to be an instance of a class that implements Watcher interface.

[java] view plain copy
  1. /** 
  2.  * AbstractZooKeeper.java 
  3.  * 版权所有(C) 2013  
  4.  * 创建:cuiran 2013-01-16 14:59:44 
  5.  */  
  6. package com.zoo.demo;  
  7.   
  8. import java.io.IOException;  
  9. import java.util.concurrent.CountDownLatch;  
  10.   
  11. import org.apache.commons.logging.Log;  
  12. import org.apache.commons.logging.LogFactory;  
  13. import org.apache.zookeeper.WatchedEvent;  
  14. import org.apache.zookeeper.Watcher;  
  15. import org.apache.zookeeper.ZooKeeper;  
  16. import org.apache.zookeeper.Watcher.Event.KeeperState;  
  17.   
  18.   
  19. /** 
  20.  * TODO 
  21.  * @author cuiran 
  22.  * @version TODO 
  23.  */  
  24. public class AbstractZooKeeper implements Watcher {  
  25.     private static Log log = LogFactory.getLog(AbstractZooKeeper.class.getName());  
  26.   
  27.     //缓存时间  
  28.      private static final int SESSION_TIME   = 2000;     
  29.      protected ZooKeeper zooKeeper;  
  30.      protected CountDownLatch countDownLatch=new CountDownLatch(1);  
  31.   
  32.      public void connect(String hosts) throws IOException, InterruptedException{     
  33.             zooKeeper = new ZooKeeper(hosts,SESSION_TIME,this);     
  34.             countDownLatch.await();     
  35.       }     
  36.   
  37.     /* (non-Javadoc) 
  38.      * @see org.apache.zookeeper.Watcher#process(org.apache.zookeeper.WatchedEvent) 
  39.      */  
  40.     @Override  
  41.     public void process(WatchedEvent event) {  
  42.         // TODO Auto-generated method stub  
  43.         if(event.getState()==KeeperState.SyncConnected){  
  44.             countDownLatch.countDown();  
  45.         }  
  46.     }  
  47.       
  48.     public void close() throws InterruptedException{     
  49.         zooKeeper.close();     
  50.     }    
  51. }  

然后写一些操作和main方法

[java] view plain copy
  1. /** 
  2.  * ZooKeeperOperator.java 
  3.  * 版权所有(C) 2013  
  4.  * 创建:cuiran 2013-01-16 15:03:40 
  5.  */  
  6. package com.zoo.demo;  
  7.   
  8. import java.util.Arrays;  
  9. import java.util.List;  
  10.   
  11. import org.apache.commons.logging.Log;  
  12. import org.apache.commons.logging.LogFactory;  
  13. import org.apache.zookeeper.CreateMode;  
  14. import org.apache.zookeeper.KeeperException;  
  15. import org.apache.zookeeper.ZooDefs.Ids;  
  16.   
  17. /** 
  18.  * TODO 
  19.  * @author cuiran 
  20.  * @version TODO 
  21.  */  
  22. public class ZooKeeperOperator extends AbstractZooKeeper {  
  23.       
  24.     private static Log log = LogFactory.getLog(ZooKeeperOperator.class.getName());  
  25.   
  26.     /** 
  27.      *  
  28.      *<b>function:</b>创建持久态的znode,比支持多层创建.比如在创建/parent/child的情况下,无/parent.无法通过 
  29.      *@author cuiran 
  30.      *@createDate 2013-01-16 15:08:38 
  31.      *@param path 
  32.      *@param data 
  33.      *@throws KeeperException 
  34.      *@throws InterruptedException 
  35.      */  
  36.     public void create(String path,byte[] data)throws KeeperException, InterruptedException{  
  37.         /** 
  38.          * 此处采用的是CreateMode是PERSISTENT  表示The znode will not be automatically deleted upon client's disconnect. 
  39.          * EPHEMERAL 表示The znode will be deleted upon the client's disconnect. 
  40.          */   
  41.         this.zooKeeper.create(path, data, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);  
  42.     }  
  43.     /** 
  44.      *  
  45.      *<b>function:</b>获取节点信息 
  46.      *@author cuiran 
  47.      *@createDate 2013-01-16 15:17:22 
  48.      *@param path 
  49.      *@throws KeeperException 
  50.      *@throws InterruptedException 
  51.      */  
  52.     public void getChild(String path) throws KeeperException, InterruptedException{     
  53.         try{  
  54.             List<String> list=this.zooKeeper.getChildren(path, false);  
  55.             if(list.isEmpty()){  
  56.                 log.debug(path+"中没有节点");  
  57.             }else{  
  58.                 log.debug(path+"中存在节点");  
  59.                 for(String child:list){  
  60.                     log.debug("节点为:"+child);  
  61.                 }  
  62.             }  
  63.         }catch (KeeperException.NoNodeException e) {  
  64.             // TODO: handle exception  
  65.              throw e;     
  66.   
  67.         }  
  68.     }  
  69.       
  70.     public byte[] getData(String path) throws KeeperException, InterruptedException {     
  71.         return  this.zooKeeper.getData(path, false,null);     
  72.     }    
  73.       
  74.      public static void main(String[] args) {  
  75.          try {     
  76.                 ZooKeeperOperator zkoperator             = new ZooKeeperOperator();     
  77.                 zkoperator.connect("192.168.0.138");  
  78.                   
  79.                 byte[] data = new byte[]{'a','b','c','d'};     
  80.                      
  81. //              zkoperator.create("/root",null);     
  82. //              System.out.println(Arrays.toString(zkoperator.getData("/root")));     
  83. //                   
  84. //              zkoperator.create("/root/child1",data);     
  85. //              System.out.println(Arrays.toString(zkoperator.getData("/root/child1")));     
  86. //                   
  87. //              zkoperator.create("/root/child2",data);     
  88. //              System.out.println(Arrays.toString(zkoperator.getData("/root/child2")));     
  89.                      
  90.                 String zktest="ZooKeeper的Java API测试";  
  91.                 zkoperator.create("/root/child3", zktest.getBytes());  
  92.                 log.debug("获取设置的信息:"+new String(zkoperator.getData("/root/child3")));  
  93.                   
  94.                 System.out.println("节点孩子信息:");     
  95.                 zkoperator.getChild("/root");     
  96.                      
  97.                 zkoperator.close();     
  98.                   
  99.                   
  100.             } catch (Exception e) {     
  101.                 e.printStackTrace();     
  102.             }     
  103.   
  104.     }  
  105. }  


最后运行结果:

[plain] view plain copy
  1. 2013-01-16 15:26:04:INFO org.apache.zookeeper.ZooKeeper - Client environment:user.name=Administrator  
  2. 2013-01-16 15:26:04:INFO org.apache.zookeeper.ZooKeeper - Client environment:user.home=C:\Documents and Settings\Administrator  
  3. 2013-01-16 15:26:04:INFO org.apache.zookeeper.ZooKeeper - Client environment:user.dir=D:\workspace\stormdemo1  
  4. 2013-01-16 15:26:04:INFO org.apache.zookeeper.ZooKeeper - Initiating client connection, connectString=192.168.0.138 sessionTimeout=2000 watcher=com.zoo.demo.ZooKeeperOperator@ca8327  
  5. 2013-01-16 15:26:04:INFO org.apache.zookeeper.ClientCnxn - Opening socket connection to server /192.168.0.138:2181  
  6. 2013-01-16 15:26:13:INFO org.apache.zookeeper.ClientCnxn - Socket connection established to 192.168.0.138/192.168.0.138:2181, initiating session  
  7. 2013-01-16 15:26:13:INFO org.apache.zookeeper.ClientCnxn - Session establishment complete on server 192.168.0.138/192.168.0.138:2181, sessionid = 0x13c3c5224cc0003, negotiated timeout = 4000  
  8. 2013-01-16 15:26:13:DEBUG com.zoo.demo.ZooKeeperOperator - 获取设置的信息:ZooKeeper的Java API测试  
  9. 节点孩子信息:  
  10. 2013-01-16 15:26:13:DEBUG com.zoo.demo.ZooKeeperOperator - /root中存在节点  
  11. 2013-01-16 15:26:13:DEBUG com.zoo.demo.ZooKeeperOperator - 节点为:child1  
  12. 2013-01-16 15:26:13:DEBUG com.zoo.demo.ZooKeeperOperator - 节点为:child3  
  13. 2013-01-16 15:26:13:DEBUG com.zoo.demo.ZooKeeperOperator - 节点为:child2  
  14. 2013-01-16 15:26:13:INFO org.apache.zookeeper.ZooKeeper - Session: 0x13c3c5224cc0003 closed  
  15. 2013-01-16 15:26:13:INFO org.apache.zookeeper.ClientCnxn - EventThread shut down