Zookeeper的java客户端Curator

常见的zookeeper java API:

  • 原生的java api
  • ZkClient
  • Curator

高版本的Curator,兼容低版本的zookeeper

Curator API 常用操作

建立连接

    @Before
    public void TestConnect() throws Exception {
        //重试策略
        ExponentialBackoffRetry exponentialBackoffRetry = new ExponentialBackoffRetry( 3000, 10 );
        client = CuratorFrameworkFactory.builder().connectString( "192.168.4.181:2181" )
                .sessionTimeoutMs( 60*100 )
                .connectionTimeoutMs( 15 * 100 )
                .retryPolicy( exponentialBackoffRetry )
                .namespace( "crh" ).build();
        //开启连接
        client.start();
    }

添加节点

 -     /**
     * 创建节点
     * 1.基本创建 create().forPath("")
     * 2.创建节点,有数据 create().forPath("",data)
     * 3.设置节点类型 create().withMode().forPath("",data)
     * 4.创建多级节点 create().creatingParentsIfNeeded().forPath("")
     */
    @Test
    public void CreateNode() throws Exception {

        String path = client.create().forPath( "/111" );
        System.out.println(path);

    }
    @Test
    public void CreateNodeData() throws Exception {

        String path = client.create().forPath( "/222" ,"hehe".getBytes());
        System.out.println(path);

    }

    @Test
    public void CreateENode() throws Exception {

        String path = client.create().withMode( CreateMode.EPHEMERAL ).forPath( "/333" ,"haha".getBytes());
        System.out.println(path);

    }

    @Test
    public void CreatePNode() throws Exception {
        String path = client.create().creatingParentsIfNeeded().forPath( "/333/33" ,"haha".getBytes());
        System.out.println(path);

    }

删除节点

/**
 * 删除节点 delete ,deleteall
 * 1.删除单个节点
 * 2.删除带有子节点的节点
 * 3.必须删除成功
 * 4.回调
 */
@Test
public void deleteNode() throws Exception {
    client.delete().forPath( "/11" );

}
@Test
public void deleteNNode() throws Exception{
    client.delete().deletingChildrenIfNeeded().forPath( "/222" );
}
@Test
public void deleteRNode() throws Exception{
    client.delete().guaranteed().forPath( "/111" );
}
@Test
public void back() throws Exception{
    //异步回调
    ExecutorService executorService = Executors.newFixedThreadPool(1);
    client.delete().guaranteed().inBackground( new BackgroundCallback() {
        @Override
        public void processResult(CuratorFramework curatorFramework, CuratorEvent curatorEvent) throws Exception {
            System.out.println("nihao");
            client.delete().forPath( "/2" );
        }
    },executorService).forPath( "/1" );
}

修改节点

  /**
     * 修改数据
     * 1.修改数据
     * 2.根据版本修改数据
     */
    @Test
    public void setData() throws Exception {
        client.setData().forPath( "/222" ,"hello".getBytes());
        byte[] bytes = client.getData().forPath( "/222" );

        System.out.println(new String( bytes ));

    }
    @Test
    public void setDataForVersion() throws Exception {
        //首先获取version
        Stat stat = new Stat();
        client.getData().storingStatIn( stat ).forPath( "/222" );
        int version = stat.getVersion();
        System.out.println(version);
        Stat stat1 = client.setData().withVersion( version ).forPath( "/222" );
        System.out.println(stat1);
    }

查询节点

/**
     * 查询节点:
     * 1.查询数据:get:   getData().forPath()
     * 2.查询子节点:ls:   getChildren().forPath()
     * 3.查询节点状态信息:ls -s:   getData().storingStatIn(状态对象).forPath()
     */
    @Test
    public void GetData() throws Exception {
        byte[] data = client.getData().forPath( "/222" );
        System.out.println(data);
        System.out.println(new String( data ));

    }

    @Test
    public void GetChildrenNode() throws Exception {
        List<String> childPath = client.getChildren().forPath( "/222" );
        System.out.println(String.valueOf( childPath ));

    }

    @Test
    public void GetNodeStatus() throws Exception {
        Stat stat = new Stat();
        System.out.println("stat---- "+stat);
        //将状态信息
        client.getData().storingStatIn( stat ).forPath( "/222" );
        System.out.println(stat);

    }

watch事件监听

/**
 * 1.监听特定节点
 * 2.监听特定节点的子节点
 * 3.监听特定节点和其子节点
 * @throws Exception
 */
@Test
public void NodeCache() throws Exception {
    //1.创建NodeCache对象
    NodeCache nodeCache = new NodeCache( client, "/222" );

    //2.注册监听
    nodeCache.getListenable().addListener( new NodeCacheListener() {
        @Override
        public void nodeChanged() throws Exception {
            System.out.println("我变化了");

            //获取修改后的节点数据
            byte[] data = nodeCache.getCurrentData().getData();
            System.out.println(new String( data ));
        }
    } );
    //3.开启监听,设置为true,则开启监听,加载缓冲数据
    nodeCache.start(true);
    while (true){

    }
}

@Test
public void NodeClildenCache() throws Exception {
    //创建监听对象
    PathChildrenCache pathChildrenCache = new PathChildrenCache( client, "/222", true );
    //绑定监听器
    pathChildrenCache.getListenable().addListener( new PathChildrenCacheListener() {
        @Override
        public void childEvent(CuratorFramework curatorFramework, PathChildrenCacheEvent pathChildrenCacheEvent) throws Exception {
            System.out.println("子节点变化了");
            System.out.println(pathChildrenCacheEvent);

            //监听子节点的数据变更,并且拿到变更后的数据
            //1.获取数据类型
            PathChildrenCacheEvent.Type type = pathChildrenCacheEvent.getType();
            if (type.equals( PathChildrenCacheEvent.Type.CHILD_UPDATED )){
                System.out.println("数据变化!!!");
                byte[] data = pathChildrenCacheEvent.getData().getData();
                System.out.println(new String( data ));
            }
        }
    } );
    //开启监听
    pathChildrenCache.start();

    while (true){

    }
}

@Test
public void TreeCache(){
    //创建监听器
    TreeCache treeCache = new TreeCache( client, "/222" );
    //注册监听
    treeCache.getListenable().addListener( new TreeCacheListener() {
        @Override
        public void childEvent(CuratorFramework curatorFramework, TreeCacheEvent treeCacheEvent) throws Exception {
            System.out.println("节点变化!!!");
            System.out.println(treeCacheEvent);
        }
    } );
}

分布式锁实现

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值