zookeeper 应用开发
由于zookeeper的client只有zookeeper一個對象,使用也比較簡單,所以就不許要文字說明了,在代碼中注釋下就ok 了。
1、測試用的main方法
package ClientExample; public class TestMain { public static void main(String[] args) { /* * 測試流程 * 1、創建sever1的連接client1,并且創建一個永久性的/test節點 * 2、創建一個針對server1的臨時節點 * 3、創建server2的連接client21,并創建一個針對server2的臨時節點 * 4、創建server3的連接client3,并創建一個針對server3的臨時節點 * 5、分別查看client1、client2、client3的三個節點的字節點數量,確定是否同步成功 * 6、修改client1的臨時節點內容,然后在在client2和client3中查看 * 7、kill掉client3的線程,然后檢查是watcher是否有通知給client1和client2 */ Thread t1= new ClientThread("127.0.0.1:2181","server1",false); Thread t2= new ClientThread("127.0.0.1:2182","server2",false); Thread t3= new ClientThread("127.0.0.1:2183","server3",false); Thread t4= new ClientThread("127.0.0.1:2181","server4",false); t1.start(); t2.start(); t3.start(); t4.start(); ControlThread c = new ControlThread(t1, t2, t3, t4); c.start(); int i=0; while(true) { i++; i--; } /* * 測試控制臺輸出: * connectIP:server4,path:null,state:SyncConnected,type:None * connectIP:server3,path:/test,state:SyncConnected,type:NodeChildrenChanged * connectIP:server4,path:/test/server4,state:SyncConnected,type:NodeCreated * 。。。。。。。。。。。 * * connectIP:server2,path:null,state:Disconnected,type:None server2exception,KeeperErrorCode = ConnectionLoss for /test connectIP:newServer1,path:null,state:SyncConnected,type:None connectIP:server1,path:/test,state:SyncConnected,type:NodeChildrenChanged connectIP:server4,path:/test/server2,state:SyncConnected,type:NodeDeleted connectIP:server4,path:/test,state:SyncConnected,type:NodeChildrenChanged connectIP:newServer1,path:/test,state:SyncConnected,type:NodeChildrenChanged connectIP:server3,path:/test/server2,state:SyncConnected,type:NodeDeleted connectIP:server3,path:/test,state:SyncConnected,type:NodeChildrenChanged */ } }
2、zookeeper封裝的接口:package ClientExample; import java.io.IOException; import java.util.List; import org.apache.zookeeper.KeeperException; /** * zookeeper的操作封裝接口,實現了常用的操作 * 創建、銷毀、寫入、修改、查詢等。 * @author ransom * */ public interface ServerOperation { void init(String address,String serverName) throws IOException; void destroy() throws InterruptedException; List<String> getChilds(String path) throws KeeperException, InterruptedException; String getData(String path) throws KeeperException, InterruptedException; void changeData(String path, String data) throws KeeperException, InterruptedException; void delData(String path) throws KeeperException, InterruptedException; void apendTempNode(String path, String data) throws KeeperException, InterruptedException; void apendPresistentNode(String path, String data) throws KeeperException, InterruptedException; void delNode(String path) throws KeeperException, InterruptedException; boolean exist(String path) throws KeeperException, InterruptedException; }
3、接口的實現:package ClientExample;import java.io.IOException; import java.util.List; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.ZooKeeper; import org.apache.zookeeper.ZooDefs.Ids; public class ServerConnector implements ServerOperation { // 創建一個Zookeeper實例,第一個參數為目標服務器地址和端口,第二個參數為Session超時時間,第三個為節點變化時的回調方法 private ZooKeeper zk = null; public void init(String address,String serverName) throws IOException { zk = new ZooKeeper(address, 500000, new MultiWatcher(serverName)); } @Override public void destroy() throws InterruptedException { // TODO Auto-generated method stub if (zk != null) { zk.close(); } } @Override public List<String> getChilds(String path) throws KeeperException, InterruptedException { // TODO Auto-generated method stub if (zk != null) { return zk.getChildren(path, true); } return null; } @Override public String getData(String path) throws KeeperException, InterruptedException { // TODO Auto-generated method stub if (zk != null) { // 取得/root/childone節點下的數據,返回byte[] byte[] b = zk.getData(path, true, null); return new String(b); } return null; } @Override public void changeData(String path,String data) throws KeeperException, InterruptedException { // TODO Auto-generated method stub if (zk != null) { // 修改節點/root/childone下的數據,第三個參數為版本,如果是-1,那會無視被修改的數據版本,直接改掉 zk.setData(path, data.getBytes(),-1); } } @Override public void delData(String path) throws InterruptedException, KeeperException { // TODO Auto-generated method stub if (zk != null) { // 刪除/root/childone這個節點,第二個參數為版本,-1的話直接刪除,無視版本 zk.delete(path, -1); } } @Override public void delNode(String path) throws InterruptedException, KeeperException { // TODO Auto-generated method stub if (zk != null) { zk.delete(path, -1); } } @Override public boolean exist(String path) throws KeeperException, InterruptedException { // TODO Auto-generated method stub if (zk != null) { return zk.exists(path, true)!=null; } return false; } @Override public void apendTempNode(String path, String data) throws KeeperException, InterruptedException { // TODO Auto-generated method stub // TODO Auto-generated method stub if (zk != null) { // 創建一個節點root,數據是mydata,不進行ACL權限控制,節點為永久性的(即客戶端shutdown了也不會消失) /* * 創建一個給定的目錄節點 path, 并給它設置數據, * CreateMode 標識有四種形式的目錄節點,分別是 * PERSISTENT:持久化目錄節點,這個目錄節點存儲的數據不會丟失; * PERSISTENT_SEQUENTIAL:順序自動編號的目錄節點,這種目錄節點會根據當前已近存在的節點數自動加 1,然后返回給客戶端已經成功創建的目錄節點名; * EPHEMERAL:臨時目錄節點,一旦創建這個節點的客戶端與服務器端口也就是 session 超時,這種節點會被自動刪除; * EPHEMERAL_SEQUENTIAL:臨時自動編號節點 */ zk.create(path, data.getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL); } } @Override public void apendPresistentNode(String path, String data) throws KeeperException, InterruptedException { // TODO Auto-generated method stub if (zk != null) { // 創建一個節點root,數據是mydata,不進行ACL權限控制,節點為永久性的(即客戶端shutdown了也不會消失) /* * 創建一個給定的目錄節點 path, 并給它設置數據, * CreateMode 標識有四種形式的目錄節點,分別是 * PERSISTENT:持久化目錄節點,這個目錄節點存儲的數據不會丟失; * PERSISTENT_SEQUENTIAL:順序自動編號的目錄節點,這種目錄節點會根據當前已近存在的節點數自動加 1,然后返回給客戶端已經成功創建的目錄節點名; * EPHEMERAL:臨時目錄節點,一旦創建這個節點的客戶端與服務器端口也就是 session 超時,這種節點會被自動刪除; * EPHEMERAL_SEQUENTIAL:臨時自動編號節點 */ zk.create(path, data.getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } } } 4、一個控制的線程,主要用來強制kill掉連接的線程
package ClientExample; public class ControlThread extends Thread{ public ControlThread(Thread t1,Thread t2,Thread t3,Thread t4) { list[0]=t1; list[1]=t2; list[2]=t4; list[3]=t4; } private Thread[] list = new Thread[4]; private int num=0; public void run() { while(true) { if(num==7) { list[2].stop(); System.out.println("kill server3"); } if(num==15) { list[3].stop(); System.out.println("kill server4"); } try { sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
5、watcher 的實現:package ClientExample; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.Watcher.Event.EventType; import org.apache.zookeeper.Watcher.Event.KeeperState; /** * 提供給多個client使用的watcher * @author ransom * */ public class MultiWatcher implements Watcher{ public MultiWatcher(String address) { connectAddress=address; } private String connectAddress=null; @Override public void process(WatchedEvent event) { // TODO Auto-generated method stub String outputStr=""; if(connectAddress!=null){ outputStr+="connectIP:"+connectAddress; } outputStr+=",path:"+event.getPath(); outputStr+=",state:"+event.getState(); outputStr+=",type:"+event.getType(); System.out.println(outputStr); } }
6、client 運行 的Threadpackage ClientExample; import java.io.IOException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import org.apache.zookeeper.KeeperException; public class ClientThread extends Thread{ public ClientThread(String address,String serverName,boolean islog) { this.address=address; this.serverName=serverName; try { otherOperation(); } catch (KeeperException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } this.islog=islog; } private boolean islog=true; private final String rootPath = "/test"; private String address; private String serverName; private ServerOperation operationCient = null; public void run() { if(operationCient==null) { System.out.println("operationCient=null"); return; } while(true){ try { if(islog){ System.out.println(serverName+",loopTime:"+getNowTime()); } observerChildData(rootPath); } catch (KeeperException e) { // TODO Auto-generated catch block System.out.println(serverName+"exception,"+e.getLocalizedMessage()); try { operationCient= new ServerConnector(); operationCient.init("127.0.0.1:2181","newServer1"); } catch (IOException e1) { // TODO Auto-generated catch block System.out.println(serverName+" reconnect exception,"+e.getLocalizedMessage()); } } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { sleep(2000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } /* * 測試流程 * 1、創建sever1的連接client1,并且創建一個永久性的/test節點 * 2、創建一個針對server1的臨時節點 * 3、創建server2的連接client21,并創建一個針對server2的臨時節點 * 4、創建server3的連接client3,并創建一個針對server3的臨時節點 * 5、分別查看client1、client2、client3的三個節點的字節點數量,確定是否同步成功 * 6、修改client1的臨時節點內容,然后在在client2和client3中查看 * 7、kill掉client3的線程,然后檢查是watcher是否有通知給client1和client2 */ private void otherOperation() throws KeeperException, InterruptedException { operationCient= new ServerConnector(); try { operationCient.init(address,serverName); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } if(operationCient==null) { System.out.println("operationCient=null"); return; } if(!operationCient.exist(rootPath)) { operationCient.apendPresistentNode(rootPath, "this node is creat by " + serverName); } //添加臨時節點 if(!operationCient.exist(rootPath+"/"+serverName)) { operationCient.apendTempNode(rootPath+"/"+serverName, "this node is creat by " + serverName); } observerChildData("/test"); //修改臨時節點內容 operationCient.changeData(rootPath+"/"+serverName, "this node is changed by " + serverName); //臨時節點內容 List<String> childs=operationCient.getChilds(rootPath); for(String str : childs) { System.out.println("observered by "+ serverName +": child node is :"+ str); } } //查看臨時節點的同步狀態 public void observerChildData(String path) throws KeeperException, InterruptedException { if(operationCient==null) { System.out.println("operationCient=null"); return; } List<String> childs=operationCient.getChilds(rootPath); if(islog){ System.out.println("observered by "+ serverName +": childs len is :"+ childs.size()); } for(String str : childs) { if(islog){ System.out.println("observered by "+ serverName +": child node is :"+ str+",data is :"+operationCient.getData(rootPath+"/"+str)); } } } public String getNowTime() { DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); return format1.format(new Date()); } }
轉載于:https://www.cnblogs.com/cl1024cl/p/6205140.html
總結
以上是生活随笔為你收集整理的zookeeper 应用开发的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Aspx 页面生命周期
- 下一篇: 基于visual Studio2013解