zookeeper生成全局ID

1、实现原理

利用zookeeper的临时有序节点生成分布式全局ID

2、java实现步骤

2.1、实现代码

package com.cn.willy;

import org.apache.zookeeper.*;

import java.util.concurrent.CountDownLatch;

public class UnIDZookeeperUtils implements Watcher {

private static final String URL="192.168.43.134:2181";

private static final int TIME_OUT=5000;

private CountDownLatch latch = new CountDownLatch(1);

private ZooKeeper zooKeeper = null;


/**
 * zookeeper监听
 * @param event
 */
public void process(WatchedEvent event) {

    if (event.getState() == Event.KeeperState.SyncConnected){
        latch.countDown();
    }else if(event.getState() == Event.KeeperState.Disconnected){
        System.out.println("disconnected");
    }
}

/**
 * 在构造函数中创建zookeeper实例
 */
public  UnIDZookeeperUtils(){
    try{
        zooKeeper = new ZooKeeper(URL,TIME_OUT,this);
        latch.await();
    }catch (Exception e){
        e.printStackTrace();
    }
}

/**
 * 创建zk临时有序节点
 * 截取序列号并返回
 * @return
 */
public String getID(String path){
    String resultId = "";
    try{
        resultId = zooKeeper.create(path,new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
    }catch (Exception e){
        e.printStackTrace();
    }
    return  resultId.replace(path,"");
}

public static void main(String[] args) {
    UnIDZookeeperUtils idZookeeperUtils = new UnIDZookeeperUtils();
    for (int i = 0 ; i < 10 ; i++){
        System.out.println(idZookeeperUtils.getID("/fsmdemp"));
    }
}
}

2.2、结果显示
zookeeper生成全局ID_第1张图片

你可能感兴趣的:(zookeeper)