zookeeper 學習(二) java操做zookeeper

碼雲`java

簡單建立一個demonode

  首先建立maven項目,在pom中引入 zookeepergit

  <dependency>
            <groupId>org.apache.zookeeper</groupId>
            <artifactId>zookeeper</artifactId>
            <version>3.6.0</version>
        </dependency>

而後在resource文件夾下 建立log4j.properties=》做爲zookeeper日誌輸出spring

log4j.rootLogger=INFO, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{HH:mm:ss} %p %c{2}: %m%n

建立一個class,操做apache

package com.item.zkjavaapi;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;

/**
 * 描述:     鏈接到ZK服務端,打印鏈接狀態
 */
public class ZKConnect implements Watcher {
    //端口
    public static final String SERVER_PATH = "127.0.0.1:2181";
    //檢測心跳過時時間-毫秒
    public static final Integer TIMEOUT = 5000;
public static void main(String[] args)
throws IOException, InterruptedException, KeeperException {

/**
* 客戶端和服務端他們是異步鏈接,鏈接成功以後,客戶端會收到watcher通知。
* connectString:服務器的IP+端口號,好比127.0.0.1:2181
* sessionTimeout:超時時間
* watcher:通知事件
*/
ZooKeeper zooKeeper = new ZooKeeper(SERVER_PATH, TIMEOUT, new ZKOperator());
System.out.println("客戶端開始鏈接ZK服務器了");
System.out.println(zooKeeper.getState());
Thread.sleep(2000);

/**
* path:建立的路徑
* data:存儲的數據
* acl:權限,開放
* createMode:永久、臨時、順序。
*/
zooKeeper.create("/demoNode1","2233".getBytes(),
ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);

//獲取
byte[] data = zooKeeper.getData("/demoNode1", null, null);
System.out.println(new String(data));
/**
* 修改
* path:節點的路徑
* data :數據
* version:版本 盤本匹配,纔去修改
*/
zooKeeper.setData("/demoNode1","3344".getBytes(),0);
data = zooKeeper.getData("/demoNode1", null, null);
System.out.println(new String(data));


//判斷節點是否存在以及獲取其版本
Stat exists = zk.exists("/demoNode1", false);
if (exists != null) {
System.out.println("節點的版本爲:" + exists.getVersion());
}else {
System.out.println("該節點不存在");
}


String ctx = "刪除成功";
zooKeeper.delete("/demoNode1", 0, new DeleteCallBack(), ctx);
Thread.sleep(2000);
}
@Override
public void process(WatchedEvent event) {
//根據類型判斷
if (event.getType() == Event.EventType.NodeDataChanged) {
System.out.println("數據被改變");

}

System.out.println("收到了通知" + event);
}

 

DeleteCallBack代碼api

package com.item.zkjavaapi.callback;

import org.apache.zookeeper.AsyncCallback;
/**
 * 描述:     刪除後運行的方法
 */
public class DeleteCallBack implements AsyncCallback.VoidCallback {
    @Override
    public void processResult(int i, String s, Object o) {
        System.out.println("刪除節點" + s);
        System.out.println((String)o);
    }
}

 

使用Apache Curator操做zookeeper服務器

  首先pom須要引用如下session

        <dependency>
            <groupId>org.apache.curator</groupId>
            <artifactId>curator-framework</artifactId>
            <version>2.12.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.curator</groupId>
            <artifactId>curator-recipes</artifactId>
            <version>2.12.0</version>
        </dependency>

 

而後代碼app

package com.item.zkjavaapi.Curator;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;

public class CuratorDemo {
    //端口
    public static final String SERVER_PATH = "127.0.0.1:2181";
    //檢測心跳過時時間-毫秒
    public static final Integer TIMEOUT = 5000;

    public static void main(String[] args) throws Exception{
        String nodePath="/demoNode2";
        //設置從新鏈接功能   ,    ;1000 從第一次重試開始已經花費的時間   3 重試次數
        RetryPolicy retry = new ExponentialBackoffRetry(1000, 3);
        CuratorFramework client = CuratorFrameworkFactory.newClient(SERVER_PATH, retry);
        client.start();
        String data = "test";
        String data2 = "test2";

        //建立節點以及肯定值
        client.create().withMode(CreateMode.PERSISTENT).forPath(nodePath,data.getBytes());
        //獲取節點的值
        byte[] bytes = client.getData().watched().forPath(nodePath);

        System.out.println(new String(bytes));
        //修改節點的值
        client.setData().forPath(nodePath,data2.getBytes());
        bytes = client.getData().watched().forPath(nodePath);
        System.out.println(new String(bytes));
        //刪除節點
        client.delete().forPath(nodePath);
        Thread.sleep(200);
    }

}
相關文章
相關標籤/搜索