使用JAVA操作zookeeper的节点

zookeeper的Znode有两种,分别为临时节点和永久节点,再加上Znode有一个序列化特性,所以一共会存在四种类型的Znode节点

  • PERSISTENT:永久节点

  • EPHEMERAL:临时节点

  • PERSISTENT_SEQUENTIAL:永久节点、序列化

  • EPHEMERAL_SEQUENTIAL:临时节点、序列化

1.使用脚本启动zookeeper集群

使用JAVA操作zookeeper的节点_第1张图片

2.创建maven工程,导入依赖


    
        org.apache.curator
        curator-framework
        2.12.0
    
    
        org.apache.curator
        curator-recipes
        2.12.0
    
    
        com.google.collections
        google-collections
        1.0
    
    
        junit
        junit
        RELEASE
    
    
        org.slf4j
        slf4j-simple
        1.7.25
    



    
        
        
            org.apache.maven.plugins
            maven-compiler-plugin
            3.2
            
                1.8
                1.8
                UTF-8
            
        
    

3.创建永久节点

/**
 * @author Jiapeng Pang
 * @Position 大数据工程师
 * @date 2019/8/15 21:58.
 */
public class zookeepertest {

    @Test
    public void createNode() throws Exception{

        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 1);

        //获取客户端对象
        CuratorFramework client = CuratorFrameworkFactory.newClient("192.168.174.100:2181,192.168.174.110:2181,192.168.174.120:2181",
                1000, 1000, retryPolicy);

        //调用start开启客户端操作
        client.start();

        //通过create 来进行创建节点,并且需要指定节点类型
        client.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT).forPath("/hello3/world");
        System.out.println("完成");
        client.close();



    }

}

前后查看结果对比

使用JAVA操作zookeeper的节点_第2张图片

4.创建临时节点

  @Test
    public void createTempNode() throws Exception{

        RetryPolicy retryPolicy = new ExponentialBackoffRetry(3000, 1);
        CuratorFramework client = CuratorFrameworkFactory.newClient("node01:2181,node02:2181,node03:2181", 3000, 3000, retryPolicy);
        client.start();
        client.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).forPath("/hello5/world");
        Thread.sleep(5000);
        client.close();

    }

查看结果

使用JAVA操作zookeeper的节点_第3张图片

修改节点数据:

/**
 * 节点下面添加数据与修改是类似的,一个节点下面会有一个数据,新的数据会覆盖旧的数据
 * @throws Exception
 */

@Test
public void nodeData() throws Exception {
    RetryPolicy retryPolicy = new  ExponentialBackoffRetry(3000, 1);
    CuratorFramework client = CuratorFrameworkFactory.newClient("node01:2181,node02:2181,node03:2181", 3000, 3000, retryPolicy);
    client.start();
    client.setData().forPath("/hello5", "hello7".getBytes());
    client.close();
}

节点数据查询:

/**
 * 数据查询
 */

@Test

public void updateNode() throws Exception {
    RetryPolicy retryPolicy = new  ExponentialBackoffRetry(3000, 1);
    CuratorFramework client = CuratorFrameworkFactory.newClient("node01:2181,node02:2181,node03:2181", 3000, 3000, retryPolicy);
    client.start();
    byte[] forPath = client.getData().forPath("/hello5");
    System.out.println(new String(forPath));
    client.close();
}

 

你可能感兴趣的:(zookeeper,zookeeper,Znode操作)