Zookeeper 簡易java客戶端

原生寫法:

package com.gcx.zookeeper;

import java.util.List;

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.ZooKeeper;
import org.apache.zookeeper.data.Stat;
import org.junit.Before;
import org.junit.Test;

public class Tests {

	private static final String connectString ="node01:2181,node02:2181,node03:2181";
	private static final int sessionTimeout=60000;
  

	ZooKeeper zkClient = null;

	@Before
	public void init() throws Exception {
		zkClient = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
			@Override
			public void process(WatchedEvent event) {
				// 收到事件通知後的回調函數(應該是我們自己的事件處理邏輯)
				System.out.println(event.getType() + "---" + event.getPath());
				try {
					zkClient.getChildren("/", true);
				} catch (Exception e) {
				}
			}
		});

	}

		/**
		 * 數據的增刪改查
		 * 
		 * @throws InterruptedException
		 * @throws KeeperException
		 */

		// 創建數據節點到zk中
		public void testCreate() throws KeeperException, InterruptedException {
			// 參數1:要創建的節點的路徑 參數2:節點大數據 參數3:節點的權限 參數4:節點的類型
			String nodeCreated = zkClient.create("/eclipse", "hellozk".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
			//上傳的數據可以是任何類型,但都要轉成byte[]
		}

		//判斷znode是否存在
		@Test	
		public void testExist() throws Exception{
			Stat stat = zkClient.exists("/eclipse", false);
			System.out.println(stat==null?"not exist":"exist");
			
			
		}
		
		// 獲取子節點
		@Test
		public void getChildren() throws Exception {
			List<String> children = zkClient.getChildren("/", true);
			for (String child : children) {
				System.out.println(child);
			}
			Thread.sleep(Long.MAX_VALUE);
		}

		//獲取znode的數據
		@Test
		public void getData() throws Exception {
			
			byte[] data = zkClient.getData("/eclipse", false, null);
			System.out.println(new String(data));
			
		}
		
		//刪除znode
		@Test
		public void deleteZnode() throws Exception {
			
			//參數2:指定要刪除的版本,-1表示刪除所有版本
			zkClient.delete("/eclipse", -1);
			
			
		}
		//刪除znode
		@Test
		public void setData() throws Exception {
			
			zkClient.setData("/app1", "imissyou angelababy".getBytes(), -1);
			
			byte[] data = zkClient.getData("/app1", false, null);
			System.out.println(new String(data));
			
		}
		
		
	}

curator框架實現zk客戶端

1.maven座標

<dependencies>
        <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>
        <dependency>
            <groupId>com.google.collections</groupId>
            <artifactId>google-collections</artifactId>
            <version>1.0</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-simple</artifactId>
            <version>1.7.25</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <!-- java編譯插件 -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.2</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
        </plugins>
    </build>

2.測試代碼:

package com.gcxzflgl;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.ChildData;
import org.apache.curator.framework.recipes.cache.TreeCache;
import org.apache.curator.framework.recipes.cache.TreeCacheEvent;
import org.apache.curator.framework.recipes.cache.TreeCacheListener;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.junit.Test;

/**
 * @author gcxzf$
 * @version : CuratorTest$, v 0.1 2020/6/26$ 08:24$ gcxzf$ Exp$
 */

public class CuratorTest {

    /**
     * 創建永久節點
     * @throws Exception
     */
    @Test
    public void createNode() throws Exception {
        //定製重試策略(連接客戶端可能存在連接失敗進行重試次數)
        // param1 重試間隔
        // param2 重試次數
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(3000, 3);

        //獲取客戶端對象
        // param1 連接zk服務列表
        // param2 會話超時時間
        // param3 連接超時時間
        // param4 重試策略
        CuratorFramework client = CuratorFrameworkFactory.newClient("node01:2181,node02:2181,node03:2181", 3000, 3000, retryPolicy);

        //啓動客戶端
        client.start();

        //創建永久節點
        client
                .create()
                .creatingParentsIfNeeded() //需要創建父節點
                .withMode(CreateMode.PERSISTENT) //節點的類型
                .forPath("/hello","words".getBytes()); //節點路徑

        //關閉客戶端
        client.close();
    }


    /**
     * 修改節點內容
     */
    @Test
    public void updateNode() throws Exception {

        RetryPolicy retryPolicy = new ExponentialBackoffRetry(3000,3);

        CuratorFramework client = CuratorFrameworkFactory.newClient("node01:2181,node02:2181,node03:2181", 3000, 3000, retryPolicy);

        client.start();

        //更新指定節點的數據
        client.setData().forPath("/hello","words_holiday".getBytes());

        client.close();
    }


    /**
     * 查看節點內容
     */
    @Test
    public void searchNode() throws Exception {

        RetryPolicy retryPolicy = new ExponentialBackoffRetry(3000,3);

        CuratorFramework client = CuratorFrameworkFactory.newClient("node01:2181,node02:2181,node03:2181", 3000, 3000, retryPolicy);

        client.start();

        //獲取指定節點的數據
        byte[] bytes = client.getData().forPath("/hello");

        System.out.println("目標節點的值:" + new String(bytes));

        client.close();
    }


    /**

     * zookeeper的watch機制

     * @throws Exception

     */
    @Test
    public void watchNode() throws Exception {

        RetryPolicy policy = new ExponentialBackoffRetry(3000, 3);

        CuratorFramework client = CuratorFrameworkFactory.newClient("node01:2181,node02:2181,node03:2181", policy);

        client.start();

        //設置節點的cache,監聽 hello
        TreeCache treeCache = new TreeCache(client, "/hello");

        //設置監聽器和處理過程
        treeCache.getListenable().addListener(new TreeCacheListener() {
            @Override
            public void childEvent(CuratorFramework client, TreeCacheEvent event) throws Exception {
                ChildData data = event.getData();
                if(data !=null){
                    switch (event.getType()) {
                        case NODE_ADDED:
                            System.out.println("NODE_ADDED : "+ data.getPath() +"  數據:"+ new String(data.getData()));
                            break;
                        case NODE_REMOVED:
                            System.out.println("NODE_REMOVED : "+ data.getPath() +"  數據:"+ new String(data.getData()));
                            break;
                        case NODE_UPDATED:
                            System.out.println("NODE_UPDATED : "+ data.getPath() +"  數據:"+ new String(data.getData()));
                            break;
                        default:
                            break;
                    }
                }else{
                    System.out.println( "data is null : "+ event.getType());
                }
            }
        });
        //開始監聽
        treeCache.start();
        Thread.sleep(50000000);

    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章