-
创建一个maven工程
<dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> <!-- 服务器上安装的zookeeper版本为 3.6.1 所以这里需要使用对应的客户端版本 --> <dependency> <groupId>org.apache.zookeeper</groupId> <artifactId>zookeeper</artifactId> <version>3.6.1</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency>
-
测试代码
public class TestZookeeper1 { //连接的zookeeper集群 private String connectString = "192.168.150.129:2181,192.168.150.130:2181,192.168.150.131:2181"; //超时时间 private int sessionTimeout = 2000; private ZooKeeper zooKeeper; //连接zookeeper集群 @Test public void init() throws IOException { //第三个参数为监听器 zooKeeper = new ZooKeeper(connectString, sessionTimeout, new Watcher() { public void process(WatchedEvent watchedEvent) { } }); } }
-
log4j配置 log4j.properties
log4j.rootLogger = debug , 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{ABSOLUTE} %5p %c:%L - %m%n
-
运行代码
以上表示连接zookeeper集群成功
-
创建一个节点
/** * 创建一个节点 * @throws KeeperException * @throws InterruptedException */ @Test public void createNode() throws KeeperException, InterruptedException { //访问权限为所有 //模式为永久模式 String path = zooKeeper.create("/study", "java".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); System.out.println(path); } //需要把上面的init()的注解配置为 @Before
-
获取子节点并监听子节点变化
/** * 获取子节点 并监听子节点的变化 * @throws KeeperException * @throws InterruptedException */ @Test public void getChildrenAndWatch() throws KeeperException, InterruptedException { List<String> children = zooKeeper.getChildren("/", true); children.forEach(System.out::println); TimeUnit.SECONDS.sleep(Long.MAX_VALUE); } @Before public void init() throws IOException { zooKeeper = new ZooKeeper(connectString, sessionTimeout, new Watcher() { public void process(WatchedEvent watchedEvent) { System.out.println("==================== start ====================="); List<String> children = null; try { children = zooKeeper.getChildren("/", true); children.forEach(System.out::println); } catch (KeeperException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("==================== end ====================="); } }); }
-
判断ZNode是否存在
/** * 判断指定ZNode是否存在 * @throws KeeperException * @throws InterruptedException */ @Test public void existsZNode() throws KeeperException, InterruptedException { Stat exists = zooKeeper.exists("/study", false); System.out.println(exists); }
-
注意
如果出现下面这种异常
是因为客户端连接超时了。
解决的办法是把 sessionTimeout = 2000; 这个值调大。
八、编写代码连接Zookeeper集群
最新推荐文章于 2023-06-26 14:35:28 发布