curator增删改查以及监视


前言
代码可以看这个
https://gitee.com/song_mengyu/Example/tree/master/Project/Zookeeper-Curator-Demos我的仓库

一、Curator

Curator是zookeeper的一个高层次封装库,为开发人员封装了zookeeper的一组开发库,它的核心目标就是为你管理Zookeeper的相关操作,将连接的复杂性隐藏起来。
Curator为开发人员实现了一组常用的操作管理的菜谱,同时结合开发过程中的最佳实践和常见的边际处理。同时也提供了流畅式开发风格的API。

二、引入依赖

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>1.5.8.RELEASE</version>
        </dependency>
        <!-- 接下来这三个是curator的依赖      -->
        <dependency>
            <groupId>org.apache.curator</groupId>
            <artifactId>curator-recipes</artifactId>
            <version>2.12.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.curator</groupId>
            <artifactId>curator-framework</artifactId>
            <version>2.12.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.curator</groupId>
            <artifactId>curator-client</artifactId>
            <version>2.12.0</version>
        </dependency>
    </dependencies>

二、增删改查

首先要创立链接,我们使用config类来创建

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.RetryOneTime;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.context.annotation.Bean;

@SpringBootConfiguration
public class Config {

    @Bean
    public CuratorFramework curatorFramework(){
        CuratorFramework client = CuratorFrameworkFactory.builder()
                .connectString("192.168.136.128:2181")
                .sessionTimeoutMs(40000)
                .retryPolicy(new RetryOneTime(40000))
                .namespace("test")
                .build();
        client.start();
        return client;
    }
}

然后我们写个controller

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.api.BackgroundCallback;
import org.apache.curator.framework.api.CuratorEvent;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooDefs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class Controller {
    @Autowired
    CuratorFramework client;

    @PostMapping("/create/{path}/{content}")    //增添节点,同步实现
    public String create (@PathVariable(value = "path") String path,
                         @PathVariable(value = "content") String content) throws Exception {
        client.create()
                .withMode(CreateMode.PERSISTENT)    //创建节点的类型
                .withACL(ZooDefs.Ids.OPEN_ACL_UNSAFE)  //节点的权限
                .forPath("/" + path, content.getBytes());  //节点路径和内容
        return "ok";
    }
    @PostMapping("/anscreate/{path}/{content}")  //增添节点异步实现
    public String anscreate (@PathVariable(value = "path") String path,
                          @PathVariable(value = "content") String content) throws Exception {
        client.create()
                .creatingParentContainersIfNeeded()  
                .withMode(CreateMode.PERSISTENT)
                .withACL(ZooDefs.Ids.OPEN_ACL_UNSAFE)
                .inBackground(new BackgroundCallback() {   //回调函数
                    @Override
                    public void processResult(CuratorFramework curatorFramework, CuratorEvent curatorEvent) throws Exception {
                        System.out.println(curatorFramework);
                        System.out.println(curatorEvent.getType());
                        System.out.println(curatorEvent.getPath());
                    }
                })
                .forPath("/" + path, content.getBytes());
        return "ok";
    }
    @GetMapping("/get/{path}")   //查询节点信息
    public String get(@PathVariable(value = "path") String path) throws Exception {
        byte[] bytes = client.getData().forPath("/" + path);
        return  new String(bytes);
    }
    @PostMapping("/update/{path}/{content}")
    public String update(@PathVariable(value = "path") String path,
                         @PathVariable(value = "content") String content) throws Exception {
        client.setData().withVersion(-1).forPath("/" + path, content.getBytes());
        return "ok";
    }
    @GetMapping("/delete/{path}")    //删除
    public String delete(@PathVariable(value = "path") String path) throws Exception {
        client.delete().withVersion(-1).forPath("/" + path);
        return "ok";
    }

}

二、监视
只监视某个节点

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.NodeCache;
import org.apache.curator.framework.recipes.cache.NodeCacheListener;
import org.apache.curator.retry.RetryOneTime;

public class Main {
    public static void main(String[] args) throws Exception {
        CuratorFramework client = CuratorFrameworkFactory.builder()
                .connectString("192.168.136.128:2181")
                .sessionTimeoutMs(40000)
                .retryPolicy(new RetryOneTime(40000))
                .namespace("watcher1")
                .build();
        client.start();

        NodeCache nodeCache = new NodeCache(client, "/watcher");
        //启动监视器
        nodeCache.start();
        nodeCache.getListenable().addListener(new NodeCacheListener() {
            @Override
            public void nodeChanged() throws Exception {
                System.out.println(nodeCache.getCurrentData().getPath());
                System.out.println(new String(nodeCache.getCurrentData().getData()));
            }
        });
        Thread.sleep(300000);
        //关闭监视器
        nodeCache.close();
        client.close();

    }
}

监视某个节点的子节点

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.PathChildrenCache;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener;
import org.apache.curator.retry.RetryOneTime;

public class Main {
    public static void main(String[] args) throws Exception {
        CuratorFramework client = CuratorFrameworkFactory.builder()
                .connectString("192.168.136.128:2181")
                .sessionTimeoutMs(40000)
                .retryPolicy(new RetryOneTime(40000))
                .namespace("watcher1")
                .build();
        client.start();

        PathChildrenCache pathChildrenCache = new PathChildrenCache(client,"/wathcer",true);
        pathChildrenCache.start();
        pathChildrenCache.getListenable().addListener(new PathChildrenCacheListener() {
            @Override
            public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {
                System.out.println("====== 节点发生了变化 ======");
                System.out.println(event.getType());
                System.out.println(event.getData().getPath());
            }
        });
        Thread.sleep(300000);
        pathChildrenCache.close();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值