使用zookeeper的java API操作zookeeper集群--maven项目

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/c5113620/article/details/88911469

maven项目,纯java api 使用zookeeper集群

//pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.dddd</groupId>
    <artifactId>maventest</artifactId>
    <version>1.0</version>

    <dependencies>
        <dependency>
            <groupId>org.apache.zookeeper</groupId>
            <artifactId>zookeeper</artifactId>
            <!-- same version with the zookeeper-->
            <version>3.4.13</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.0</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>
//Test.java
import org.apache.log4j.BasicConfigurator;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

import java.util.List;
import java.util.concurrent.CountDownLatch;

public class Test {

    public static void main(String[] args) throws Exception{

        //quick log4j config
        BasicConfigurator.configure();

        ZkWatcher zkWatcher = new ZkWatcher();
        Stat stat = new Stat();
        // zookeeper conn is async, so wait to trigger the watcher
        ZooKeeper zk = new ZooKeeper("192.168.11.131:2181", 3000, zkWatcher);
        zkWatcher.waitToConn();

        System.out.println(zk.getState());

        String path = "/";
        List<String> children = zk.getChildren(path,null);
        for(String child:children){
            System.out.println("find "+child+" :");
            System.out.println("   "+new String(zk.getData(path+child,true,stat)));
        }

        zk.close();
    }
}

class ZkWatcher implements Watcher{
    private static CountDownLatch connectedSemaphore = new CountDownLatch(1);

    @Override
    public void process(WatchedEvent watchedEvent) {
        if (Event.KeeperState.SyncConnected == watchedEvent.getState()){
            connectedSemaphore.countDown();
        }
    }

    public void waitToConn() throws Exception{
        connectedSemaphore.await();
    }
}

猜你喜欢

转载自blog.csdn.net/c5113620/article/details/88911469