码迷,mamicode.com
首页 > 编程语言 > 详细

zookeeper_03:Java 客户端(原生API)

时间:2016-08-28 19:30:03      阅读:151      评论:0      收藏:0      [点我收藏+]

标签:

  • 环境配置
  1. 下载并ZooKeeper的发行版
  2. 新建Java project,并导入jar包
  • 创建会话

public class CreateSession implements Watcher { 

private static ZooKeeper zookeeper;

public static void main(String[] args) throws IOException, InterruptedException {

  zookeeper = new ZooKeeper("192.168.1.105:2181",5000,new CreateSession());

  System.out.println(zookeeper.getState());

  Thread.sleep(Integer.MAX_VALUE);

  }

  private void doSomething(){

    System.out.println("do something");

  }

public void process(WatchedEvent event) {

  System.out.println("收到事件:"+event);

  if (event.getState()==KeeperState.SyncConnected){

    if (event.getType()==EventType.None && null==event.getPath()){

      doSomething();

    }

  }

  }

}

  •  同步创建节点

public class CreateNodeSync implements Watcher {

  private static ZooKeeper zookeeper;
  public static void main(String[] args) throws IOException, InterruptedException {
    zookeeper = new ZooKeeper("192.168.124.128:2181,192.168.124.128:2182,192.168.124.128:2183",5000,new CreateNodeSync());
    System.out.println(zookeeper.getState());

    Thread.sleep(Integer.MAX_VALUE);
  }

  private void doSomething(){
    try {
      String path = zookeeper.create("/test", "test".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
      System.out.println("return path:"+path);
    } catch (KeeperException e) {
      e.printStackTrace();
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
      System.out.println("do something");
    }
  public void process(WatchedEvent event) {
    System.out.println("收到事件:"+event);
    if (event.getState()==KeeperState.SyncConnected){
      if (event.getType()==EventType.None && null==event.getPath()){
        doSomething();
      }
    }
  }
}

  • 异步创建节点

import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.EventType;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.ZooDefs.Perms;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.ACL;
import org.apache.zookeeper.data.Id;
import org.apache.zookeeper.server.auth.DigestAuthenticationProvider;


public class CreateNodeSyncAuth implements Watcher {

  private static ZooKeeper zookeeper;
  private static boolean somethingDone = false;

  public static void main(String[] args) throws IOException, InterruptedException {
    zookeeper = new ZooKeeper("192.168.124.128:2181,192.168.124.128:2182,192.168.124.128:2183",5000,new CreateNodeSyncAuth());
    System.out.println(zookeeper.getState());

    Thread.sleep(Integer.MAX_VALUE);
  }
  /*
  * 权限模式(scheme): ip, digest
  * 授权对象(ID)
  * ip权限模式: 具体的ip地址
  * digest权限模式: username:Base64(SHA-1(username:password))
  * 权限(permission): create(C), DELETE(D),READ(R), WRITE(W), ADMIN(A)
  * 注:单个权限,完全权限,复合权限
  *
  * 权限组合: scheme + ID + permission
  *
  *
  *
  * */
  private void doSomething(){
    try {

      ACL aclIp = new ACL(Perms.READ,new Id("ip","192.168.124.128"));
      ACL aclDigest = new ACL(Perms.READ|Perms.WRITE,new Id("digest",DigestAuthenticationProvider.generateDigest("zhangsan:123456")));
      ArrayList<ACL> acls = new ArrayList<ACL>();
      acls.add(aclDigest);
      acls.add(aclIp);
      //zookeeper.addAuthInfo("digest", "zhangsan:123456".getBytes());
      String path = zookeeper.create("/test", "test".getBytes(), acls, CreateMode.PERSISTENT);
      System.out.println("return path:"+path);

      somethingDone = true;

    } catch (KeeperException e) {
      e.printStackTrace();
    } catch (InterruptedException e) {
      e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
  public void process(WatchedEvent event) {
    
    System.out.println("收到事件:"+event);
    if (event.getState()==KeeperState.SyncConnected){
      if (!somethingDone && event.getType()==EventType.None && null==event.getPath()){
        doSomething();
      }
    }
  }
}


StringCallback{

   public void (int rc,String path,Object ctx,String name)

}

    rc是result code 服务端响应结果码。客户端可以从这个结果码中识别出API的调用结果,常见的结果码有:

      0(OK),接口调用成功

      -4(ConnectionLoss),客户端和服务器连接断开

     -110(NodeExists) 节点已存在

    -112(SessionExpired)会话已过期

   path: 接口调用传入的数据节点的节点路径

   ctx: 接口调用传入的ctx参数

 

  name: 实际在服务器端创建的节点名


  • 同步删除节点


import java.io.IOException;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.EventType;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.ZooKeeper;

public class DeleteNodeSync implements Watcher{


  private static ZooKeeper zooKeeper;
  public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
    zooKeeper = new ZooKeeper("192.168.1.105:2181",5000,new DeleteNodeSync());
    System.out.println(zooKeeper.getState().toString());

    Thread.sleep(Integer.MAX_VALUE);

  }

  private void doSomething(ZooKeeper zooKeeper){
    try {
      zooKeeper.delete("/node_7", -1);
    } catch (InterruptedException e) {
      e.printStackTrace();
    } catch (KeeperException e) {
      e.printStackTrace();
    }
  }

  @Override
  public void process(WatchedEvent event) {
    if (event.getState()==KeeperState.SyncConnected){
      if (event.getType()==EventType.None && null==event.getPath()){
        doSomething(zooKeeper);
      }
    }
  }
}

  • 异步删除节点

import java.io.IOException;

import org.apache.zookeeper.AsyncCallback;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.EventType;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.ZooKeeper;

public class DeleteNodeASync implements Watcher{

  private static ZooKeeper zooKeeper;
  public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
    zooKeeper = new ZooKeeper("192.168.1.105:2181",5000,new DeleteNodeASync());
    System.out.println(zooKeeper.getState().toString());
    Thread.sleep(Integer.MAX_VALUE);
  }

  private void doSomething(WatchedEvent event){
    zooKeeper.delete("/node_6", -1, new IVoidCallback(),null);
  }

  public void process(WatchedEvent event) {
    if (event.getState()==KeeperState.SyncConnected){
      if (event.getType()==EventType.None && null==event.getPath()){
        doSomething(event);
      }
    }
  }

  static class IVoidCallback implements AsyncCallback.VoidCallback{
    public void processResult(int rc, String path, Object ctx) {
      StringBuilder sb = new StringBuilder();
      sb.append("rc="+rc).append("\n");
      sb.append("path"+path).append("\n");
      sb.append("ctx="+ctx).append("\n");
      System.out.println(sb.toString());
    }
  }

}

  • 同步读取节点

 

import java.io.IOException;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.EventType;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;


public class GetDataSync implements Watcher{
  private static ZooKeeper zooKeeper;
  private static Stat stat = new Stat();

  public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
    zooKeeper = new ZooKeeper("192.168.1.105:2181",5000,new GetDataSync());
    System.out.println(zooKeeper.getState().toString());
    Thread.sleep(Integer.MAX_VALUE);
  }

  private void doSomething(ZooKeeper zookeeper){
    zookeeper.addAuthInfo("digest", "jike:123456".getBytes());
    try {
      System.out.println(new String(zooKeeper.getData("/node_4", true, stat)));
    } catch (KeeperException e) {
      e.printStackTrace();
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }

  public void process(WatchedEvent event) {
    if (event.getState()==KeeperState.SyncConnected){
      if (event.getType()==EventType.None && null==event.getPath()){
        doSomething(zooKeeper);
      }else{
        if (event.getType()==EventType.NodeDataChanged){
          try {
            System.out.println(new String(zooKeeper.getData(event.getPath(), true, stat)));
            System.out.println("stat:"+stat);
          } catch (KeeperException e) {
            e.printStackTrace();
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
        }
      }

    }
  }

}

  • 异步读取节点

 

import java.io.IOException;

import org.apache.zookeeper.AsyncCallback;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.EventType;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

public class GetDataASync implements Watcher{
  private static ZooKeeper zooKeeper;
  public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
    zooKeeper = new ZooKeeper("192.168.1.105:2181",5000,new GetDataASync());
    System.out.println(zooKeeper.getState().toString());
    Thread.sleep(Integer.MAX_VALUE);
  }

  private void doSomething(ZooKeeper zookeeper){
    zooKeeper.getData("/node_1", true, new IDataCallback(), null);
  }

  public void process(WatchedEvent event) {
    if (event.getState()==KeeperState.SyncConnected){
      if (event.getType()==EventType.None && null==event.getPath()){
        doSomething(zooKeeper);
      }else{
        if (event.getType()==EventType.NodeDataChanged){
          try {
            zooKeeper.getData(event.getPath(), true, new IDataCallback(), null);
          } catch (Exception e) {
            e.printStackTrace();
          }
        }
      }
  }
}

  static class IDataCallback implements AsyncCallback.DataCallback{
    public void processResult(int rc, String path, Object ctx, byte[] data,Stat stat) {
      try {
        System.out.println(new String(zooKeeper.getData(path, true, stat)));
        System.out.println("stat:"+stat);
      } catch (KeeperException e) {
        e.printStackTrace();
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
  }
}

  • 同步节点检测


import java.io.IOException;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.EventType;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

public class NodeExistsSync implements Watcher{


  private static ZooKeeper zooKeeper;
  public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
    zooKeeper = new ZooKeeper("192.168.1.105:2181",5000,new NodeExistsSync());
    System.out.println(zooKeeper.getState().toString());
    Thread.sleep(Integer.MAX_VALUE);
  }

  private void doSomething(ZooKeeper zooKeeper){
    try{
      Stat stat = zooKeeper.exists("/node_1", true);
      System.out.println(stat);
    }catch(Exception e){
    }
  }

  @Override
  public void process(WatchedEvent event) {
    if (event.getState()==KeeperState.SyncConnected){
      if (event.getType()==EventType.None && null==event.getPath()){
        doSomething(zooKeeper);
      }else{
        try {
          if (event.getType()==EventType.NodeCreated){
            System.out.println(event.getPath()+" created");
            System.out.println(zooKeeper.exists(event.getPath(), true));
          }
          else if (event.getType()==EventType.NodeDataChanged){
            System.out.println(event.getPath()+" updated");
            System.out.println(zooKeeper.exists(event.getPath(), true));
          }
          else if (event.getType()==EventType.NodeDeleted){
            System.out.println(event.getPath()+" deleted");
            System.out.println(zooKeeper.exists(event.getPath(), true));
          }

         } catch (Exception e) {
         }
      }
    }
  }
}

  • 异步检测节点

 

import java.io.IOException;

import org.apache.zookeeper.AsyncCallback;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.EventType;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

public class NodeExistsASync implements Watcher{
  private static ZooKeeper zooKeeper;
  public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
  zooKeeper = new ZooKeeper("192.168.1.105:2181",5000,new NodeExistsASync());
  System.out.println(zooKeeper.getState().toString());
  Thread.sleep(Integer.MAX_VALUE);
}

private void doSomething(ZooKeeper zookeeper){
  zooKeeper.exists("/node_1", true, new IStateCallback(), null);
}

public void process(WatchedEvent event) {

if (event.getState()==KeeperState.SyncConnected){
  if (event.getType()==EventType.None && null==event.getPath()){
    doSomething(zooKeeper);
  }else{
    try {
      if (event.getType()==EventType.NodeCreated){
        System.out.println(event.getPath()+" created");
        zooKeeper.exists(event.getPath(), true, new IStateCallback(), null);
      }
      else if (event.getType()==EventType.NodeDataChanged){
        System.out.println(event.getPath()+" updated");
        zooKeeper.exists(event.getPath(), true, new IStateCallback(), null);
      }
      else if (event.getType()==EventType.NodeDeleted){
        System.out.println(event.getPath()+" deleted");
        zooKeeper.exists(event.getPath(), true, new IStateCallback(), null);
      }
    } catch (Exception e) {
    }
  }
}

}


static class IStateCallback implements AsyncCallback.StatCallback{

    public void processResult(int rc, String path, Object ctx, Stat stat) {
      System.out.println("rc:"+rc);
    }
  }
}

  • 同步获取子节点

 

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

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.EventType;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.ZooKeeper;
public class GetChildrenSync implements Watcher{
  private static ZooKeeper zooKeeper;
  public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
    zooKeeper = new ZooKeeper("192.168.1.105:2181",5000,new GetChildrenSync());
    System.out.println(zooKeeper.getState().toString());
    Thread.sleep(Integer.MAX_VALUE);
  }

  private void doSomething(ZooKeeper zooKeeper){
    try {
      List<String> children = zooKeeper.getChildren("/", true);
      System.out.println(children);
    } catch (Exception e) {
    }
  }

  public void process(WatchedEvent event) {
    if (event.getState()==KeeperState.SyncConnected){
      if (event.getType()==EventType.None && null==event.getPath()){
        doSomething(zooKeeper);
      }else{
        if (event.getType()==EventType.NodeChildrenChanged){
          try {
            System.out.println(zooKeeper.getChildren(event.getPath(), true));
          } catch (KeeperException e) {
            e.printStackTrace();
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
        }
      }
    }
  }
}

  • 异步获取子节点

 

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

import org.apache.zookeeper.AsyncCallback;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.EventType;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

public class GetChildrenASync implements Watcher{
  private static ZooKeeper zooKeeper;
  public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
    zooKeeper = new ZooKeeper("192.168.1.105:2181",5000,new GetChildrenASync());
    System.out.println(zooKeeper.getState().toString());
    Thread.sleep(Integer.MAX_VALUE);
  }

  private void doSomething(ZooKeeper zookeeper){
    try {
      zooKeeper.getChildren("/", true, new IChildren2Callback(), null);
    } catch (Exception e) {
    }
  }

  public void process(WatchedEvent event) {
    if (event.getState()==KeeperState.SyncConnected){
      if (event.getType()==EventType.None && null==event.getPath()){
        doSomething(zooKeeper);
      }else{
        if (event.getType()==EventType.NodeChildrenChanged){
          zooKeeper.getChildren(event.getPath(), true, new IChildren2Callback(), null);
        }
      }
    }
  }

  static class IChildren2Callback implements AsyncCallback.Children2Callback{
    public void processResult(int rc, String path, Object ctx,List<String> children, Stat stat) {
      StringBuilder sb = new StringBuilder();
      sb.append("rc="+rc).append("\n");
      sb.append("path="+path).append("\n");
      sb.append("ctx="+ctx).append("\n");
      sb.append("children="+children).append("\n");
      sb.append("stat="+stat).append("\n");
      System.out.println(sb.toString());
    }
  }
}

  • 同步更新


import java.io.IOException;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.EventType;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

public class UpdateNodeSync implements Watcher{
  private static ZooKeeper zooKeeper;
  public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
    zooKeeper = new ZooKeeper("192.168.1.105:2181",5000,new UpdateNodeSync());
    System.out.println(zooKeeper.getState().toString());
    Thread.sleep(Integer.MAX_VALUE);
  }
  private void doSomething(ZooKeeper zooKeeper){
    try {
      Stat stat = zooKeeper.setData("/node_6", "123".getBytes(), -1);
      System.out.println("stat:"+stat);
    } catch (InterruptedException e) {
      e.printStackTrace();
    } catch (KeeperException e) {
    e.printStackTrace();
    }
  }

  public void process(WatchedEvent event) {
    if (event.getState()==KeeperState.SyncConnected){
      if (event.getType()==EventType.None && null==event.getPath()){
        doSomething(zooKeeper);
      }
    }
  }
}

  • 异步更新


import java.io.IOException;

import org.apache.zookeeper.AsyncCallback;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.EventType;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

public class UpdateNodeASync implements Watcher{

  private static ZooKeeper zooKeeper;
  public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
    zooKeeper = new ZooKeeper("192.168.1.105:2181",5000,new UpdateNodeASync());
    System.out.println(zooKeeper.getState().toString());
    Thread.sleep(Integer.MAX_VALUE);
  }

  private void doSomething(WatchedEvent event){
    zooKeeper.setData("/node_6", "234".getBytes(), -1, new IStatCallback(),null);
  }

  public void process(WatchedEvent event) {
    if (event.getState()==KeeperState.SyncConnected){
      if (event.getType()==EventType.None && null==event.getPath()){
        doSomething(event);
      }
    }
  }

  static class IStatCallback implements AsyncCallback.StatCallback{

    public void processResult(int rc, String path, Object ctx, Stat stat) {
      StringBuilder sb = new StringBuilder();
      sb.append("rc="+rc).append("\n");
      sb.append("path"+path).append("\n");
      sb.append("ctx="+ctx).append("\n");
      sb.append("Stat="+stat).append("\n");
      System.out.println(sb.toString());
    }
  }
}

zookeeper_03:Java 客户端(原生API)

标签:

原文地址:http://www.cnblogs.com/FS372/p/5815594.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!