Zookeeper全局唯一ID

系统唯一ID生成分案有很多种,例如:数据库 auto_increment,UUID,Redis生成ID(Redis原子操作INCR和INCRBY),Twiitter的snowflake算法,ZooKeeper生成ID,MongoDb的ObjectId,下面我们就看一下ZooKeeper实现分布式系统唯一ID。

public int idGen() throws Exception {
    String zkAddress = "127.0.0.1:2181";
    String idNode = "/id";

    //重试策略
    RetryPolicy retry = new RetryNTimes(3, 2000);
    //创建连接客户端
    CuratorFramework client = CuratorFrameworkFactory.builder().
            connectString(zkAddress).
            sessionTimeoutMs(5000).
            connectionTimeoutMs(10000).
            retryPolicy(retry).
            build();
    //启动客户端
    client.start();

    if (null == client.checkExists().forPath(idNode)) {
        client.create().withMode(CreateMode.PERSISTENT)
                .forPath(idNode);
    }
    Stat stat = client.setData().withVersion(-1).forPath(idNode);
    return stat.getVersion();
}

注意:换了ZooKeeper,数据就要从0开始,还没有直接可以修改指定数字那里开始,只能写程序一点点的创建,直到达到你要想的数据 ,这是它最大的弊端。

时刻与技术进步,每天一点滴,日久一大步!!! 本博客只为记录,用于学习,如有冒犯,请私信于我。
原文地址:https://www.cnblogs.com/myitnews/p/13747232.html