前言
代码可以看这个
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();
}
}