zookeeper - java操作

來源:互聯網
上載者:User

標籤:

ZKUtils.java

package test;import java.io.IOException;import java.util.concurrent.CountDownLatch;import org.apache.zookeeper.WatchedEvent;import org.apache.zookeeper.Watcher;import org.apache.zookeeper.ZooKeeper;import org.apache.zookeeper.Watcher.Event.KeeperState;public class ZKUtils {public static ZooKeeper openZk() throws IOException, InterruptedException {//串連zookeeper成功的標誌final CountDownLatch connectedSignal = new CountDownLatch(1);ZooKeeper zk = new ZooKeeper(Test.connectString, Test.sessionTimeout, new Watcher() {@Overridepublic void process(WatchedEvent event) {if(KeeperState.SyncConnected.equals(event.getState())) {//串連成功則開啟當前進程connectedSignal.countDown();}}});//對CountDownLatch對象調用await()方法後,當前線程會堵塞等待,直到對象的計數器為0(調用對象的countDown()方法減1)//堵塞當前進程connectedSignal.await();return zk;}}

  

Test.java

package test;import java.io.IOException;import java.security.NoSuchAlgorithmException;import java.util.ArrayList;import java.util.List;import java.util.concurrent.CountDownLatch;import org.apache.zookeeper.AsyncCallback.VoidCallback;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.ZooDefs.Perms;import org.apache.zookeeper.ZooKeeper;import org.apache.zookeeper.data.ACL;import org.apache.zookeeper.data.Id;import org.apache.zookeeper.data.Stat;import org.apache.zookeeper.server.auth.DigestAuthenticationProvider;public class Test {public static final String connectString = "hadoop1:2181";public static final int sessionTimeout = 5000;public static void main(String[] args) throws Exception {//建立path//createZnode("/b");//列出子znode//listChildren("/");//delete("/b");//deleteAsynchronous("/b");//watch();//強制用戶端已連線的服務區跟領導者進行同步,以更新指定path的狀態,只能是非同步呼叫sync();/* * 驗證 *///auth1();//auth2();}/** * 建立znode * @param path * @throws IOException * @throws InterruptedException * @throws KeeperException */private static void createZnode(String path) throws IOException, InterruptedException,KeeperException {ZooKeeper zk = ZKUtils.openZk();String createdPath = zk.create(path, null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);System.out.println("建立" + createdPath + "成功");// 建立znode, 資料是hello, ACL(存取控制清單)是完全放開的列表, 短暫類型的znode(session斷開後,znode將被zookeeper伺服器刪除)//String createdPath = zk.create(path, "hello".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);// 這裡列印的是//System.out.println(createdPath);// 順序的短暫znode//createdPath = zk.create(path, "hello".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);// 這裡列印的是path000000000N, 路徑名+10位的序號//System.out.println(createdPath);}/** * 列出子znode * @param parent * @throws IOException * @throws InterruptedException * @throws KeeperException */private static void listChildren(String parent) throws IOException, InterruptedException, KeeperException {ZooKeeper zk = ZKUtils.openZk();Stat state = zk.exists(parent, false);if(state == null) {return;}List<String> children = zk.getChildren(parent, false);for (String child : children) {System.out.println(child);}}/** * 刪除znode及其子znode * @param path * @throws IOException * @throws InterruptedException * @throws KeeperException */private static void delete(String path) throws IOException, InterruptedException, KeeperException {ZooKeeper zk = ZKUtils.openZk();Stat state = zk.exists(path, false);if(state == null) {return;}System.out.println(state.getVersion());List<String> children = zk.getChildren(path, false);for (String child : children) {delete(path + "/" + child);}//需要指定path和version, version為-1則取消版本號碼驗證zk.delete(path, -1);}/** * 非同步作業 * zookeeper同時提供同步、非同步兩個版本的API,業務對讀取效率沒影響的情況下選擇哪個方式都可以. * @param path * @throws IOException * @throws InterruptedException * @throws KeeperException */private static void deleteAsynchronous(String path) throws IOException, InterruptedException, KeeperException {ZooKeeper zk = ZKUtils.openZk();Stat state = zk.exists(path, false);if(state == null) {return;}List<String> children = zk.getChildren(path, false);for (String child : children) {delete(path + "/" + child);}//需要指定path和version, version為-1則取消版本號碼驗證//zk.delete(path, -1);zk.delete(path, -1, new VoidCallback() {@Overridepublic void processResult(int rc, String path, Object ctx) {System.out.println("非同步刪除操作執行完畢 , rc: " + rc + ", path: " + path);}}, null);//等待一會, 否則主線程直接結束了就看不到非同步線程的輸出結果了Thread.sleep(2000);}/** * 監聽事件 * @throws IOException * @throws InterruptedException * @throws KeeperException */private static void watch() throws IOException, InterruptedException, KeeperException {final CountDownLatch singal = new CountDownLatch(1);ZooKeeper zk = new ZooKeeper("hadoop1:2181", 5000, new Watcher() {@Overridepublic void process(WatchedEvent event) {System.out.println("接受到了一個事件:" + event);if(Watcher.Event.KeeperState.SyncConnected.equals(event.getState())) {singal.countDown();}}});singal.await();//exists、getData、getChildren操作可以設定監控//判斷"/b"是否存在並對其進行監控, 使用建立zookeeper時的watcher處理zk.exists("/b", true);//使用指定的watcher處理//zk.exists("/b", new Watcher());Thread.sleep(Long.MAX_VALUE);}/** * 強制用戶端已連線的服務器跟領導者進行同步,以更新指定znode的狀態 * 只能非同步呼叫 * @throws IOException * @throws InterruptedException * @throws KeeperException */private static void sync() throws IOException, InterruptedException, KeeperException {ZooKeeper zk = ZKUtils.openZk();zk.sync("/a", new VoidCallback(){@Overridepublic void processResult(int rc, String path, Object ctx) {try {Thread.sleep(3000);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("同步完畢");}}, null);System.out.println("here");Stat stat = zk.exists("/a", false);byte[] data = zk.getData("/a", false, stat);System.out.println("data: " + new String(data));Thread.sleep(5000);}/** * 使用自訂ACL建立znode * @throws IOException * @throws InterruptedException * @throws KeeperException * @throws NoSuchAlgorithmException */private static void auth1() throws IOException, InterruptedException, KeeperException, NoSuchAlgorithmException {List<ACL> acls = new ArrayList<ACL>();//使用者名稱密碼驗證方式Id id = new Id("digest", DigestAuthenticationProvider.generateDigest("lisg:123456"));acls.add(new ACL(Perms.READ, id));ZooKeeper zk = ZKUtils.openZk();zk.create("/c", "test".getBytes(), acls, CreateMode.PERSISTENT);}/** * ACL驗證 * @throws IOException * @throws InterruptedException * @throws KeeperException */private static void auth2() throws IOException, InterruptedException, KeeperException {ZooKeeper zk = ZKUtils.openZk();Stat stat = zk.exists("/c", false);if(stat == null) {return;}List<ACL> cacls = zk.getACL("/c", stat);System.out.println("/c的ACL列表是:" + cacls);//KeeperErrorCode = NoAuth for /c 異常zk.addAuthInfo("digest", "lisg:123456".getBytes());byte[] data = zk.getData("/c", false, stat);System.out.println("data: " + new String(data));}}

  

zookeeper - java操作

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.