當(dāng)前位置:首頁 > IT技術(shù) > Windows編程 > 正文

ZooKeeper快速入門系列(6) | Zookeeper的API操作
2021-09-02 14:16:54

??本篇博客博主為大家?guī)砥诖丫玫年P(guān)于ZooKeeper的JavaAPI操作。


一. IDEA環(huán)境搭建

1.1 創(chuàng)建一個(gè)Maven工程

1.2 添加Porn文件

<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.apache.logging.log4j</groupId>
			<artifactId>log4j-core</artifactId>
			<version>2.8.2</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.apache.zookeeper/zookeeper -->
		<dependency>
			<groupId>org.apache.zookeeper</groupId>
			<artifactId>zookeeper</artifactId>
			<version>3.4.10</version>
		</dependency>
</dependencies>

1.3 拷貝log4j.properties文件到項(xiàng)目根目錄

需要在項(xiàng)目的src/main/resources目錄下,新建一個(gè)文件,命名為“l(fā)og4j.properties”,在文件中填入。

log4j.rootLogger=INFO, stdout  
log4j.appender.stdout=org.apache.log4j.ConsoleAppender  
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout  
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n  
log4j.appender.logfile=org.apache.log4j.FileAppender  
log4j.appender.logfile.File=target/spring.log  
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout  
log4j.appender.logfile.layout.ConversionPattern=%d %p [%c] - %m%n  

二. API操作

前提(測試是否正常連接)

package com.buwenbuhuo.zookeeper;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.junit.Before;
import org.junit.Test;

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

/**
 * @author 卜溫不火
 * @create 2020-04-27 22:01
 * com.buwenbuhuo.zookeeper - the name of the target package where the new class or interface will be created.
 * ZooKeeper0427 - the name of the current project.
 */
public class ZkClient {
    private ZooKeeper zkCli;
    private static final String CONNECT_STRING = "hadoop002:2181,hadoop003:2181,hadoop004:2181";
    private static final int SESSION_TIMEOUT = 2000;

//    @Before
//    public void before() throws IOException {
//        zkCli = new ZooKeeper(CONNECT_STRING, SESSION_TIMEOUT, new Watcher() {
//            public void process(WatchedEvent watchedEvent) {
//
//            }
//        });
//    }
    // 此部分為上部分的簡寫
    @Before
    public void before() throws IOException {
        zkCli = new ZooKeeper(CONNECT_STRING, SESSION_TIMEOUT, e -> {
            System.out.println("默認(rèn)回調(diào)函數(shù)");
        });
    }

    @Test
    public void ls() throws KeeperException,InterruptedException{
        List<String> children = zkCli.getChildren("/",true);
        System.out.println("===========================================");
        for (String child: children){
            System.out.println(child);
        }
        System.out.println("===========================================");

        Thread.sleep(Long.MAX_VALUE);
    }
}

2.1 創(chuàng)建ZooKeeper客戶端


private static String connectString =
 "hadoop002:2181,hadoop003:2181,hadoop004:2181";
	private static int sessionTimeout = 2000;
	private ZooKeeper zkClient = null;

	@Before
	public void init() throws Exception {

	zkClient = new ZooKeeper(connectString, sessionTimeout, new Watcher() {

			@Override
			public void process(WatchedEvent event) {

				// 收到事件通知后的回調(diào)函數(shù)(用戶的業(yè)務(wù)邏輯)
				System.out.println(event.getType() + "--" + event.getPath());

				// 再次啟動(dòng)監(jiān)聽
				try {
					zkClient.getChildren("/", true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}


2.2 創(chuàng)建子節(jié)點(diǎn)

// 創(chuàng)建子節(jié)點(diǎn)
@Test
public void create() throws Exception {

		// 參數(shù)1:要?jiǎng)?chuàng)建的節(jié)點(diǎn)的路徑; 參數(shù)2:節(jié)點(diǎn)數(shù)據(jù) ; 參數(shù)3:節(jié)點(diǎn)權(quán)限 ;參數(shù)4:節(jié)點(diǎn)的類型
		String nodeCreated = zkClient.create("/sanguo", "jinlian".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}


2.4 獲取子節(jié)點(diǎn)并監(jiān)聽節(jié)點(diǎn)變化

// 獲取子節(jié)點(diǎn)
@Test
public void getChildren() throws Exception {

		List<String> children = zkClient.getChildren("/", true);

		for (String child : children) {
			System.out.println(child);
		}

		// 延時(shí)阻塞
		Thread.sleep(Long.MAX_VALUE);
}

2.5 判斷Znode是否存在

// 判斷znode是否存在
@Test
public void exist() throws Exception {

	Stat stat = zkClient.exists("/IDEA", false);

	System.out.println(stat == null ? "not exist" : "exist");
}

2.6 基礎(chǔ)操作案例

public static void main(String[] args) throws Exception {
        // 初始化 ZooKeeper實(shí)例(zk地址、會話超時(shí)時(shí)間,與系統(tǒng)默認(rèn)一致、watcher)
        ZooKeeper zk = new ZooKeeper("hadoop002:2181,hadoop003,hadoop004", 30000, new Watcher() {
            @Override
            public void process(WatchedEvent event) {
                System.out.println("事件類型為:" + event.getType());
                System.out.println("事件發(fā)生的路徑:" + event.getPath());
                System.out.println("通知狀態(tài)為:" +event.getState());
            }
        });
	zk.create("/myGirls", "性感的".getBytes("UTF-8"), Ids.OPEN_ACL_UNSAFE,
		 CreateMode.PERSISTENT);
      zk.close();

2.7 更多實(shí)例操作

public static void main(String[] args) throws Exception {
        // 初始化 ZooKeeper實(shí)例(zk地址、會話超時(shí)時(shí)間,與系統(tǒng)默認(rèn)一致、watcher)
        ZooKeeper zk = new ZooKeeper("hadoop002:2181,hadoop003,hadoop004", 30000, new Watcher() {
            @Override
            public void process(WatchedEvent event) {
                System.out.println("事件類型為:" + event.getType());
                System.out.println("事件發(fā)生的路徑:" + event.getPath());
                System.out.println("通知狀態(tài)為:" +event.getState());
            }
        });
    // 創(chuàng)建一個(gè)目錄節(jié)點(diǎn)
 zk.create("/testRootPath", "testRootData".getBytes(), Ids.OPEN_ACL_UNSAFE,
   CreateMode.PERSISTENT); 
 // 創(chuàng)建一個(gè)子目錄節(jié)點(diǎn)
 zk.create("/testRootPath/testChildPathOne", "testChildDataOne".getBytes(),
   Ids.OPEN_ACL_UNSAFE,CreateMode.PERSISTENT); 
 System.out.println(new String(zk.getData("/testRootPath",false,null))); 
 // 取出子目錄節(jié)點(diǎn)列表
 System.out.println(zk.getChildren("/testRootPath",true)); 
 // 修改子目錄節(jié)點(diǎn)數(shù)據(jù)
 zk.setData("/testRootPath/testChildPathOne","modifyChildDataOne".getBytes(),-1); 
 System.out.println("目錄節(jié)點(diǎn)狀態(tài):["+zk.exists("/testRootPath",true)+"]"); 
 // 創(chuàng)建另外一個(gè)子目錄節(jié)點(diǎn)
 zk.create("/testRootPath/testChildPathTwo", "testChildDataTwo".getBytes(), 
   Ids.OPEN_ACL_UNSAFE,CreateMode.PERSISTENT); 
 System.out.println(new String(zk.getData("/testRootPath/testChildPathTwo",true,null))); 
 // 刪除子目錄節(jié)點(diǎn)
 zk.delete("/testRootPath/testChildPathTwo",-1); 
 zk.delete("/testRootPath/testChildPathOne",-1); 
 // 刪除父目錄節(jié)點(diǎn)
 zk.delete("/testRootPath",-1);
 zk.close();
}

API操作比較偏向基礎(chǔ),博主在此把注釋寫了上去。


ZooKeeper快速入門系列(6) | Zookeeper的API操作_zookeeper

??好了,本次本次的分享就到這里,大家有什么疑惑可以在評論區(qū)留言或者私信博主哦。
?? 看 完 就 贊 , 養(yǎng) 成 習(xí) 慣 ! ! ! color{#FF0000}{看完就贊,養(yǎng)成習(xí)慣?。?!} 養(yǎng)習(xí)!!^ _ ^ ?? ?? ??
??碼字不易,大家的支持就是我堅(jiān)持下去的動(dòng)力。點(diǎn)贊后不要忘了關(guān)注我哦!

本文摘自 :https://blog.51cto.com/u

開通會員,享受整站包年服務(wù)立即開通 >