本文目录:
- 1、配置mycat-eye,怎么页面提示注册zookeeper
- 2、curator里面的NodeCache监听节点,怎么获取触发事件
- 3、如何使用Cruator监听zookeeper事件变化
- 4、Curator简介
- 5、如何使用cruator监听zookeeper事件变化
- 6、dubbo使用zookeeper连接,zookeeper宕机后怎么处理?
配置mycat-eye,怎么页面提示注册zookeeper
1,配置文件同步2,主从切换3,分布式队列4,分布式锁5,其他在以前的文章里面有写过使用zookeeper原生的api,监听zk节点变化,那么本篇我们就来看下,如何使用curator来完成监听,代码如下:packagecom.qin.curator.zk;importjavax.sound.midi.Patch;importorg.apache.curator.RetryPolicy;importorg.apache.curator.framework.CuratorFramework;importorg.apache.curator.framework.CuratorFrameworkFactory;importorg.apache.curator.framework.CuratorFrameworkFactory.Builder;importorg.apache.curator.framework.api.CuratorWatcher;importorg.apache.curator.framework.recipes.cache.NodeCache;importorg.apache.curator.framework.recipes.cache.NodeCacheListener;importorg.apache.curator.framework.recipes.cache.PathChildrenCache;importorg.apache.curator.framework.recipes.cache.PathChildrenCacheEvent;importorg.apache.curator.framework.recipes.cache.PathChildrenCacheListener;importorg.apache.curator.retry.ExponentialBackoffRetry;importorg.apache.curator.utils.ZKPaths;importorg.apache.zookeeper.WatchedEvent;/****使用curator监听zookeeper节点*@authorqindongliang***/publicclassCuratorWatch{staticCuratorFrameworkzkclient=null;staticStringnameSpace=”php”;static{Stringzkhost=”192.168.46.22:2181″;//zk的hostRetryPolicyrp=newExponentialBackoffRetry(1000,3);//重试机制Builderbuilder=CuratorFrameworkFactory.builder().connectString(zkhost).connectionTimeoutMs(5000).sessionTimeoutMs(5000).retryPolicy(rp);builder.namespace(nameSpace);CuratorFrameworkzclient=builder.build();zkclient=zclient;zkclient.start();//放在这前面执行zkclient.newNamespaceAwareEnsurePath(nameSpace);}publicstaticvoidmain(String[]args)throwsException{watch();Thread.sleep(Long.MAX_VALUE);}/****监听节点变化***/publicstaticvoidwatch()throwsException{PathChildrenCachecache=newPathChildrenCache(zkclient,”/zk”,false);cache.start();System.out.println(“监听开始/zk..”);PathChildrenCacheListenerplis=newPathChildrenCacheListener(){@OverridepublicvoidchildEvent(CuratorFrameworkclient,PathChildrenCacheEventevent)throwsException{switch(event.getType()){caseCHILD_ADDED:{System.out.println(“Nodeadded:”+ZKPaths.getNodeFromPath(event.getData().getPath()));break;}caseCHILD_UPDATED:{System.out.println(“Nodechanged:”+ZKPaths.getNodeFromPath(event.getData().getPath()));break;}caseCHILD_REMOVED:{System.out.println(“Noderemoved:”+ZKPaths.getNodeFromPath(event.getData().getPath()));break;}}}};//注册监听cache.getListenable().addListener(plis);}}运行后的控制台打印:18:33:07.722[main]INFOo.a.c.f.imps.CuratorFrameworkImpl-Starting18:33:07.727[main]DEBUGo.a.curator.CuratorZookeeperClient-Starting18:33:07.727[main]DEBUGorg.apache.curator.ConnectionState-Starting18:33:07.727[main]DEBUGorg.apache.curator.ConnectionState-reset18:33:07.734[main]INFOorg.apache.zookeeper.ZooKeeper-Clientenvironment:zookeeper.version=3.4.6-1569965,builton02/20/201409:09GMT18:33:07.734[main]INFOorg.apache.zookeeper.ZooKeeper-Clientenvironment:host.name=QINDONGLIANG.dhgatecn.msf18:33:07.734[main]INFOorg.apache.zookeeper.ZooKeeper-Clientenvironment:java.version=1.7.0_0418:33:07.734[main]INFOorg.apache.zookeeper.ZooKeeper-Clientenvironment:java.vendor=OracleCorporation18:33:07.734[main]INFOorg.apache.zookeeper.ZooKeeper-Clientenvironment:java.home=D:\Java\jdk1.7.0_04\jre18:33:07.734[main]INFOorg.apache.zookeeper.ZooKeeper-Clientenvironment:java.class.path=D:\eclipseworkspace2yw\opzk\bin;D:\eclipseworkspace2yw\opzk\lib\curator-client-2.6.0.jar;D:\eclipseworkspace2yw\opzk\lib\curator-examples-2.6.0.jar;D:\eclipseworkspace2yw\opzk\lib\curator-framework-2.6.0.jar;D:\eclipseworkspace2yw\opzk\lib\curator-recipes-2.6.0.jar;D:\eclipseworkspace2yw\opzk\lib\curator-test-2.6.0.jar;D:\eclipseworkspace2yw\opzk\lib\curator-x-discovery-2.6.0.jar;D:\eclipseworkspace2yw\opzk\lib\curator-x-discovery-server-2.6.0.jar;D:\eclipseworkspace2yw\opzk\lib\curator-x-rpc-2.6.0.jar;D:\eclipseworkspace2yw\opzk\lib\log4j-1.2.15.jar;D:\eclipseworkspace2yw\opzk\lib\zookeeper-3.4.5.jar;D:\eclipseworkspace2yw\opzk\lib\commons-io-2.1.jar
curator里面的NodeCache监听节点,怎么获取触发事件
判断节点是新增、修改还是删除应该通过PathChildrenCache来处理,PathChildrenCacheListener有event参数,
NodeCache和NodeCacheListener是监听节点内容变更的,直接通过cn.getCurrentData().data()可以获得节点最新内容
如何使用Cruator监听zookeeper事件变化
您好,掌握zookeeper事件监听机制,非常重要,可以说是跨入了进阶的门槛,只有掌握了如何监听某个节点或路径,我们才能在节点变化后,做一些我们想做的事,包括:
1,配置文件同步
2,主从切换
3,分布式队列
4,分布式锁
5,其他
散仙,在以前的文章里面有写过使用zookeeper原生的api,监听zk节点变化,那么本篇我们就来看下,如何使用curator来完成监听,代码如下:
pre name=”code” class=”cha-b930-3acb-c789-70de java”package com.qin.curator.zk;
import javax.sound.midi.Patch;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.CuratorFrameworkFactory.Builder;
import org.apache.curator.framework.api.CuratorWatcher;
import org.apache.curator.framework.recipes.cache.NodeCache;
import org.apache.curator.framework.recipes.cache.NodeCacheListener;
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.ExponentialBackoffRetry;
import org.apache.curator.utils.ZKPaths;
import org.apache.zookeeper.WatchedEvent;
/**
*
* 使用curator监听zookeeper节点
* @author qindongliang
* **/
public class CuratorWatch {
static CuratorFramework zkclient=null;
static String nameSpace=”php”;
static {
String zkhost=”192.168.46.22:2181″;//zk的host
RetryPolicy rp=new ExponentialBackoffRetry(1000, 3);//重试机制
Builder builder = CuratorFrameworkFactory.builder().connectString(zkhost)
.connectionTimeoutMs(5000)
.sessionTimeoutMs(5000)
.retryPolicy(rp);
builder.namespace(nameSpace);
CuratorFramework zclient = builder.build();
zkclient=zclient;
zkclient.start();// 放在这前面执行
zkclient.newNamespaceAwareEnsurePath(nameSpace);
}
public static void main(String[] args) throws Exception{
watch();
Thread.sleep(Long.MAX_VALUE);
}
/**
*
* 监听节点变化
*
* */
public static void watch()throws Exception{
PathChildrenCache cache = new PathChildrenCache(zkclient, “/zk”, false);
cache.start();
System.out.println(“监听开始/zk……..”);
PathChildrenCacheListener plis=new PathChildrenCacheListener() {
@Override
public void childEvent(CuratorFramework client, PathChildrenCacheEvent event)
throws Exception {
switch ( event.getType() )
{
case CHILD_ADDED:
{
System.out.println(“Node added: ” + ZKPaths.getNodeFromPath(event.getData().getPath()));
break;
}
case CHILD_UPDATED:
{
System.out.println(“Node changed: ” + ZKPaths.getNodeFromPath(event.getData().getPath()));
break;
}
case CHILD_REMOVED:
{
System.out.println(“Node removed: ” + ZKPaths.getNodeFromPath(event.getData().getPath()));
break;
}
}
}
};
//注册监听
cache.getListenable().addListener(plis);
}
}
/pre
运行后的控制台打印:
pre name=”code” class=”cha-3acb-c789-70de-c9c6 java”18:33:07.722 [main] INFO o.a.c.f.imps.CuratorFrameworkImpl – Starting
18:33:07.727 [main] DEBUG o.a.curator.CuratorZookeeperClient – Starting
18:33:07.727 [main] DEBUG org.apache.curator.ConnectionState – Starting
18:33:07.727 [main] DEBUG org.apache.curator.ConnectionState – reset
18:33:07.734 [main] INFO org.apache.zookeeper.ZooKeeper – Client environment:zookeeper.version=3.4.6-1569965, built on 02/20/2014 09:09 GMT
18:33:07.734 [main] INFO org.apache.zookeeper.ZooKeeper – Client environment:host.name=QINDONGLIANG.dhgatecn.msf
18:33:07.734 [main] INFO org.apache.zookeeper.ZooKeeper – Client environment:java.version=1.7.0_04
18:33:07.734 [main] INFO org.apache.zookeeper.ZooKeeper – Client environment:java.vendor=Oracle Corporation
18:33:07.734 [main] INFO org.apache.zookeeper.ZooKeeper – Client environment:java.home=D:\Java\jdk1.7.0_04\jre
18:33:07.734 [main] INFO org.apache.zookeeper.ZooKeeper – Client environment:java.class.path=D:\eclipseworkspace2yw\opzk\bin;D:\eclipseworkspace2yw\opzk\lib\curator-client-2.6.0.jar;D:\eclipseworkspace2yw\opzk\lib\curator-examples-2.6.0.jar;D:\eclipseworkspace2yw\opzk\lib\curator-framework-2.6.0.jar;D:\eclipseworkspace2yw\opzk\lib\curator-recipes-2.6.0.jar;D:\eclipseworkspace2yw\opzk\lib\curator-test-2.6.0.jar;D:\eclipseworkspace2yw\opzk\lib\curator-x-discovery-2.6.0.jar;D:\eclipseworkspace2yw\opzk\lib\curator-x-discovery-server-2.6.0.jar;D:\eclipseworkspace2yw\opzk\lib\curator-x-rpc-2.6.0.jar;D:\eclipseworkspace2yw\opzk\lib\log4j-1.2.15.jar;D:\eclipseworkspace2yw\opzk\lib\zookeeper-3.4.5.jar;D:\eclipseworkspace2yw\opzk\lib\commons-io-2.1.jar
Curator简介
一、Curator是NetFlix公司开源的一套Zookeeper客户端框架,其特点如下:
1、连接重连
2、反复注册Watcher
3、NodeExistsException处理
二、常用API
API文档对应地址:
RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);//Zookeeper每1秒检查一次session状态,如果断掉的话,重新连接,如果连续3次均没连上,则session失效
CuratorFramework client = CuratorFrameworkFactory.newClient(connectingString,sessionTimeout,connectionTimeOut,retryPolicy);
//创建节点
client.create().forPath(path);
//创建节点并设置值
client.create().forPath(path,”init”.getBytes());
//创建临时节点
client.create().withMode(CreateMode.EPHEMERAL).forPath(path);
//创建临时节点并递归创建父节点
client.create().creatingParentContainersIfNeeded().withMode(CreateMode.EPHEMERAL).forPath(path);
//删除节点
client.delete().forPath(path);
//删除节点并递归删除其所有子节点
client.delete().deletingChildrenIfNeeded().forPath(path);
//删除节点,强制指定版本进行删除
client.delete().withVersion(version).forPath(path);
//强制保证删除
client.delete().guaranteed().forPath(path);
//获取某个节点数据
client.getData().forPath(path);
//读取一个节点的数据内容,同时按获取到该节点的stat
Stat stat = new Stat();
client.getData().storingStatIn(stat).forPath(path);
//更新一个节点的数据内容
client.setData().withVersion(version).forPath(path);
//异步
client.create().creatingParentsIfNeeded().inBackground(new BackgroundCallback() {
@Override
public void processResult(CuratorFramework curatorFramework, CuratorEvent curatorEvent) throws Exception {
}
}).forPath(path,”init”.getBytes());
三、监听器
1、NodeCache:监听节点变化
NodeCache cache = new NodeCache(client,path,false);
cache.start(true); //第一次启动的时候就会从Zookeeper上同步数据
cache.getListenable().addListener(new NodeCacheListener() {
@Override
public void nodeChanged() throws Exception {
System.out.println(cache.getCurrentData().getData());
}
});
2、PathChildrenCache:监控某个节点子节点的变化【无法对父节点以及二级节点数据进行监控】
PathChildrenCache childrenCache = new PathChildrenCache(client,path,true);
childrenCache.start(PathChildrenCache.StartMode.POST_INITIALIZED_EVENT);
childrenCache.getListenable().addListener(new PathChildrenCacheListener() {
@Override
public void childEvent(CuratorFramework curatorFramework, PathChildrenCacheEvent pathChildrenCacheEvent) throws Exception {
System.out.println(“节点变更类型:”+pathChildrenCacheEvent.getType()+”对应节点:”+pathChildrenCacheEvent.getData().getPath());
}
});
四、LeaderLatch
LeaderLatch⽤于实现Leader的选举
– 触发方法isLeader(),表示成为leader
– 触发notLeader(),表示失去leader权限
– 场景:参考xxx-callback
public void afterPropertiesSet() throws Exception {
if (leaderLatch != null) {
return;
}
leaderLatch = new LeaderLatch(curatorClient,//zk客户端实例
PATH,//选举根节点路径
OSUtils.getServerIp() + “_” + UUID.randomUUID().toString()); //客户端ID,用来标记客户端,即客户端编号,名称
leaderLatch.addListener(new LeaderLatchListener() {
@Override
public void isLeader() { //抢主成功时触发
ContextHolder.setLeader(true);
LOGGER.info(“im leader”);
}
@Override
public void notLeader() { //抢主失败时触发
ContextHolder.setLeader(false);
LOGGER.info(“im not leader”);
}
});
leaderLatch.start();
}
五、分布式锁
1、模拟并发
CountDownLatch countDownLatch = new CountDownLatch(1);
for (int i=0;i10;i++){
new Thread(new Runnable() {
@Override
public void run() {
try {
countDownLatch.await();
}catch (Exception e){
}
System.out.println(System.currentTimeMillis());
}
}).start();
}
countDownLatch.countDown();
2、分布式锁控制
client.start();
String lock_path = “/lock”;
final InterProcessMutex lock = new InterProcessMutex(client,lock_path);
CountDownLatch countDownLatch = new CountDownLatch(1);
for (int i=0;i10;i++){
new Thread(new Runnable() {
@Override
public void run() {
try {
countDownLatch.await();
lock.acquire();
}catch (Exception e){
}
System.out.println(System.currentTimeMillis());
try {
lock.release();
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
countDownLatch.countDown();
六、分布式计数器
DistributedAtomicInteger atomicInteger = new DistributedAtomicInteger(client,path,new RetryNTimes(1000,3));
atomicInteger.add(8);
思考:
1、开关同步采用Zookeeper是否可以 ?
2、ABTest?
3、分批任务计算?
4、配置中心
如何使用cruator监听zookeeper事件变化
掌握zookeeper事件监听机制,非常重要,可以说是跨入了进阶的门槛,只有掌握了如何监听某个节点或路径,我们才能在节点变化后,做一些我们想做的事,包括:
1,配置文件同步
2,主从切换
3,分布式队列
4,分布式锁
5,其他
散仙,在以前的文章里面有写过使用zookeeper原生的api,监听zk节点变化,那么本篇我们就来看下,如何使用curator来完成监听,代码如下:
pre name=”code” class=”cha-c789-70de-c9c6-9e72 java”package com.qin.curator.zk;
import javax.sound.midi.Patch;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.CuratorFrameworkFactory.Builder;
import org.apache.curator.framework.api.CuratorWatcher;
import org.apache.curator.framework.recipes.cache.NodeCache;
import org.apache.curator.framework.recipes.cache.NodeCacheListener;
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.ExponentialBackoffRetry;
import org.apache.curator.utils.ZKPaths;
import org.apache.zookeeper.WatchedEvent;
/**
*
* 使用curator监听zookeeper节点
* @author qindongliang
* **/
public class CuratorWatch {
static CuratorFramework zkclient=null;
static String nameSpace=”php”;
static {
String zkhost=”192.168.46.22:2181″;//zk的host
RetryPolicy rp=new ExponentialBackoffRetry(1000, 3);//重试机制
Builder builder = CuratorFrameworkFactory.builder().connectString(zkhost)
.connectionTimeoutMs(5000)
.sessionTimeoutMs(5000)
.retryPolicy(rp);
builder.namespace(nameSpace);
CuratorFramework zclient = builder.build();
zkclient=zclient;
zkclient.start();// 放在这前面执行
zkclient.newNamespaceAwareEnsurePath(nameSpace);
}
public static void main(String[] args) throws Exception{
watch();
Thread.sleep(Long.MAX_VALUE);
}
/**
*
* 监听节点变化
*
* */
public static void watch()throws Exception{
PathChildrenCache cache = new PathChildrenCache(zkclient, “/zk”, false);
cache.start();
System.out.println(“监听开始/zk……..”);
PathChildrenCacheListener plis=new PathChildrenCacheListener() {
@Override
public void childEvent(CuratorFramework client, PathChildrenCacheEvent event)
throws Exception {
switch ( event.getType() )
{
case CHILD_ADDED:
{
System.out.println(“Node added: ” + ZKPaths.getNodeFromPath(event.getData().getPath()));
break;
}
case CHILD_UPDATED:
{
System.out.println(“Node changed: ” + ZKPaths.getNodeFromPath(event.getData().getPath()));
break;
}
case CHILD_REMOVED:
{
System.out.println(“Node removed: ” + ZKPaths.getNodeFromPath(event.getData().getPath()));
break;
}
}
}
};
//注册监听
cache.getListenable().addListener(plis);
}
}
/pre
运行后的控制台打印:
pre name=”code” class=”cha-0ea8-feb0-6be8-a035 java”18:33:07.722 [main] INFO o.a.c.f.imps.CuratorFrameworkImpl – Starting
18:33:07.727 [main] DEBUG o.a.curator.CuratorZookeeperClient – Starting
18:33:07.727 [main] DEBUG org.apache.curator.ConnectionState – Starting
18:33:07.727 [main] DEBUG org.apache.curator.ConnectionState – reset
18:33:07.734 [main] INFO org.apache.zookeeper.ZooKeeper – Client environment:zookeeper.version=3.4.6-1569965, built on 02/20/2014 09:09 GMT
18:33:07.734 [main] INFO org.apache.zookeeper.ZooKeeper – Client environment:host.name=QINDONGLIANG.dhgatecn.msf
18:33:07.734 [main] INFO org.apache.zookeeper.ZooKeeper – Client environment:java.version=1.7.0_04
18:33:07.734 [main] INFO org.apache.zookeeper.ZooKeeper – Client environment:java.vendor=Oracle Corporation
18:33:07.734 [main] INFO org.apache.zookeeper.ZooKeeper – Client environment:java.home=D:\Java\jdk1.7.0_04\jre
18:33:07.734 [main] INFO org.apache.zookeeper.ZooKeeper – Client environment:java.class.path=D:\eclipseworkspace2yw\opzk\bin;D:\eclipseworkspace2yw\opzk\lib\curator-client-2.6.0.jar;D:\eclipseworkspace2yw\opzk\lib\curator-examples-2.6.0.jar;D:\eclipseworkspace2yw\opzk\lib\curator-framework-2.6.0.jar;D:\eclipseworkspace2yw\opzk\lib\curator-recipes-2.6.0.jar;D:\eclipseworkspace2yw\opzk\lib\curator-test-2.6.0.jar;D:\eclipseworkspace2yw\opzk\lib\curator-x-discovery-2.6.0.jar;D:\eclipseworkspace2yw\opzk\lib\curator-x-discovery-server-2.6.0.jar;D:\eclipseworkspace2yw\opzk\lib\curator-x-rpc-2.6.0.jar;D:\eclipseworkspace2yw\opzk\lib\log4j-1.2.15.jar;D:\eclipseworkspace2yw\opzk\lib\zookeeper-3.4.5.jar;D:\eclipseworkspace2yw\opzk\lib\commons-io-2.1.jar
dubbo使用zookeeper连接,zookeeper宕机后怎么处理?
1、配置文件同步
2、主从切换
3、分布式队列
4、分布式锁
Zookeeper 作为一个分布式的服务框架,主要用来解决分布式集群中应用系统的一致性问题,它能提供基于类似于文件系统的目录节点树方式的数据存储,但是 Zookeeper 并不是用来专门存储数据的,它的作用主要是用来维护和监控你存储的数据的状态变化。
通过监控这些数据状态的变化,从而可以达到基于数据的集群管理,后面将会详细介绍 Zookeeper 能够解决的一些典型问题,这里先介绍一下,Zookeeper 的操作接口和简单使用示例。
常用接口列表
客户端要连接 Zookeeper 服务器可以通过创建 org.apache.zookeeper. ZooKeeper 的一个实例对象,然后调用这个类提供的接口来和服务器交互。
前面说了 ZooKeeper 主要是用来维护和监控一个目录节点树中存储的数据的状态,所有我们能够操作 ZooKeeper 的也和操作目录节点树大体一样,如创建一个目录节点,给某个目录节点设置数据,获取某个目录节点的所有子目录节点,给某个目录节点设置权限和监控这个目录节点的状态变化。
【Nodecache】的内容来源于互联网,如引用不当,请联系我们修改。