zookeeper服务器环境搭建参考
zookeeper
zookeeper在java下使用
1.pom 引入对应的包
<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
<version>3.4.6</version>
</dependency>
2.java代码
public class zkCilent {
//服务器地址 如果有坏的会尝试连接其它地址
private static final String connectStr = "192.168.2.231:2181,192.168.2.232:2181,192.168.2.233:2181";
//服务器请求超时时间
private static final int sessionTimeOut = 2000;
//zookeeper对象
private static ZooKeeper zooKeeper = null;
//线程锁count为1
private static CountDownLatch latch = new CountDownLatch(1);
//初始化连接
public static void init() throws Exception {
zooKeeper = new ZooKeeper(connectStr, sessionTimeOut, new Watcher() {
//当监听到回调需要执行的方法
public void process(WatchedEvent watchedEvent) {
// 当服务器返回响应,建立连接
if (latch.getCount() > 0 && watchedEvent.getState()== Event.KeeperState.SyncConnected){
System.out.println("count-1");
//count-1=0解除阻塞
latch.countDown();
}
//事件处理
System.out.println("type:"+watchedEvent.getType()+",path:"+watchedEvent.getPath()+",state:"+watchedEvent.getState());
}
});
//线程阻塞
latch.await();
}
//创建节点
public static void create() throws KeeperException, InterruptedException {
//创建一个节点 参数1路径,2值,3访问权限,4模式
/*3权限参数
OPEN_ACL_UNSAFE 所有人可见 常用
CREATOR_ALL_ACL 创建者全权限
READ_ACL_UNSAFE 所有人只读
4模式
持久PERSISTENT,
持久序列PERSISTENT_SEQUENTIAL,
短暂EPHEMERAL,
短暂序列EPHEMERAL_SEQUENTIAL
*/
zooKeeper.create("/testdata","hello,zk".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,CreateMode.PERSISTENT);
zooKeeper.close();
}
//修改
public static void update()throws KeeperException, InterruptedException{
//-1表示所有版本
zooKeeper.setData("/testdata","hello.zkk".getBytes(),-1);
}
//查询
public static String get()throws KeeperException, InterruptedException {
//stat 版本信息,null获取最近版本 watch表示是否监听
byte[] bytes = zooKeeper.getData("/testdata",true,null);
return new String(bytes);
}
//查询子节点
public static String getChild()throws KeeperException, InterruptedException {
//stat 版本信息,null获取最近版本 watch表示是否监听
List<String> strings = zooKeeper.getChildren("/testdata",true);
return strings.toString();
}
//删除
public static void delete()throws KeeperException, InterruptedException {
zooKeeper.delete("/testdata",-1);
}
//节点是否存在
public static boolean exists()throws KeeperException, InterruptedException {
Stat stat = zooKeeper.exists("/testdata",true);
return stat==null?false:true;
}
public static void main(String[] args) {
try {
init();
/*create();*/
update();
System.out.println(get());
} catch (Exception e) {
e.printStackTrace();
}
}
}
上下线动态感知
服务器上线时,在servsers下注册一个自己的ip节点(临时),断开连接自动断开
客户机动态监听servers下子节点变化,监听回调时,将获取servers下所有子节点
分布式共享锁
客户机连接zookeeper时,注册一把锁,即在节点locks下创建子节点,类型为临时有序列(临时节点防止客户访问时挂掉,造成死锁)
然后立刻获取locks下所有子节点并监听,如果childrenNodes只有1个。。就是自己,可直接访问共享资源,访问完成后将自己的锁节点删除;
如果里面有其它子节点,首先过滤是子节点发生改变的事件,将自己的路径截取出来,放入所有子节点中比较,如果是最小的就执行业务,之后删除自己的节点。否则就继续等待子节点发生变化。
如果业务是多个,完成一次后重新注册新的锁
网友评论