ZK生成全局id

  • Post author:
  • Post category:其他



优点:可靠,不会重复,无单点问题


缺点:只能分配32位序列号;效率不高




依赖:

<dependency>
          <groupId>com.github.adyliu</groupId>
          <artifactId>zkclient</artifactId>
          <version>2.1.1</version>
</dependency>




准备zk:


连接zkCli,建立节点seq,命令:create /seq data1  (删除命令 rmr /seq)


代码实现:


package com.xx.xx;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.github.zkclient.ZkClient;
import org.apache.zookeeper.data.Stat;

/**
 * Created by xdc on 2017/2/27 15:24.
 */
public class Test {
    
    public static final String SEQ_ZNODE = "/seq";
    static long s = System.currentTimeMillis();

    //通过znode数据版本实现分布式seq生成
    public static class Task1 implements Runnable {
        private final String taskName;
        public Task1(String taskName) {
            this.taskName = taskName;
        }

        public void run() {
            ZkClient zkClient = new ZkClient("127.0.0.1:2181", 3000, 50000);
            Stat stat =zkClient.writeData(SEQ_ZNODE, new byte[0], -1);
            int versionAsSeq = stat.getVersion();
            System.out.println(taskName + " obtain seq=" +versionAsSeq );
           
            if(versionAsSeq == 9999){
                System.out.println(System.currentTimeMillis() - s);
            }
            zkClient.close();
        }
    }

    public static void main(String[] args) {
        
        final ExecutorService service = Executors.newFixedThreadPool(20);

        for (int i = 0; i < 10000; i++) {
            service.execute(new Task1("[Concurrent-" + i + "]"));
        }
    }
}


结果:


[Concurrent-9989] obtain seq=23037

[Concurrent-9992] obtain seq=23039

[Concurrent-9990] obtain seq=23040

[Concurrent-9993] obtain seq=23041

[Concurrent-9994] obtain seq=23043

[Concurrent-9995] obtain seq=23042

[Concurrent-9996] obtain seq=23044

[Concurrent-9997] obtain seq=23045


性能:生成1w条,用时62411毫秒,平均生成用时6.24毫秒



版权声明:本文为gongzi2311原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。