zoukankan      html  css  js  c++  java
  • 分布式的Id生成器

    项目中需要一个分布式的Id生成器,twitter的Snowflake中这个既简单又高效,网上找的Java版本

    package com.cqfc.id;
    
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    
    /**
     * tweeter的snowflake 移植到Java:
     *   (a) id构成: 42位的时间前缀 + 10位的节点标识 + 12位的sequence避免并发的数字(12位不够用时强制得到新的时间前缀)
     *       注意这里进行了小改动: snowkflake是5位的datacenter加5位的机器id; 这里变成使用10位的机器id
     *   (b) 对系统时间的依赖性非常强,需关闭ntp的时间同步功能。当检测到ntp时间调整后,将会拒绝分配id
     */
    
    public class IdWorker {
    
        private final static Logger logger = LoggerFactory.getLogger(IdWorker.class);
    
        private final long workerId;
        private final long epoch = 1403854494756L;   // 时间起始标记点,作为基准,一般取系统的最近时间
        private final long workerIdBits = 10L;      // 机器标识位数
        private final long maxWorkerId = -1L ^ -1L << this.workerIdBits;// 机器ID最大值: 1023
        private long sequence = 0L;                   // 0,并发控制
        private final long sequenceBits = 12L;      //毫秒内自增位
    
        private final long workerIdShift = this.sequenceBits;                             // 12
        private final long timestampLeftShift = this.sequenceBits + this.workerIdBits;// 22
        private final long sequenceMask = -1L ^ -1L << this.sequenceBits;                 // 4095,111111111111,12位
        private long lastTimestamp = -1L;
    
        private IdWorker(long workerId) {
            if (workerId > this.maxWorkerId || workerId < 0) {
                throw new IllegalArgumentException(String.format("worker Id can't be greater than %d or less than 0", this.maxWorkerId));
            }
            this.workerId = workerId;
        }
    
        public synchronized long nextId() throws Exception {
            long timestamp = this.timeGen();
            if (this.lastTimestamp == timestamp) { // 如果上一个timestamp与新产生的相等,则sequence加一(0-4095循环); 对新的timestamp,sequence从0开始
                this.sequence = this.sequence + 1 & this.sequenceMask;
                if (this.sequence == 0) {
                    timestamp = this.tilNextMillis(this.lastTimestamp);// 重新生成timestamp
                }
            } else {
                this.sequence = 0;
            }
    
            if (timestamp < this.lastTimestamp) {
                logger.error(String.format("clock moved backwards.Refusing to generate id for %d milliseconds", (this.lastTimestamp - timestamp)));
                throw new Exception(String.format("clock moved backwards.Refusing to generate id for %d milliseconds", (this.lastTimestamp - timestamp)));
            }
    
            this.lastTimestamp = timestamp;
            return timestamp - this.epoch << this.timestampLeftShift | this.workerId << this.workerIdShift | this.sequence;
        }
    
        private static IdWorker flowIdWorker = new IdWorker(1);
        public static IdWorker getFlowIdWorkerInstance() {
            return flowIdWorker;
        }
    
    
    
        /**
         * 等待下一个毫秒的到来, 保证返回的毫秒数在参数lastTimestamp之后
         */
        private long tilNextMillis(long lastTimestamp) {
            long timestamp = this.timeGen();
            while (timestamp <= lastTimestamp) {
                timestamp = this.timeGen();
            }
            return timestamp;
        }
    
        /**
         * 获得系统当前毫秒数
         */
        private static long timeGen() {
            return System.currentTimeMillis();
        }
    
        public static void main(String[] args) throws Exception {
            System.out.println(timeGen());
    
            IdWorker idWorker = IdWorker.getFlowIdWorkerInstance();
            // System.out.println(Long.toBinaryString(idWorker.nextId()));
            System.out.println(idWorker.nextId());
            System.out.println(idWorker.nextId());
        }
    
    }
  • 相关阅读:
    mysql密码重置
    利用python生成定制二维码
    totnado前后端分离跨域设置
    supervisor详解
    redis持久化常识和配置
    redis数据的备份与恢复
    supervisor下更换源文件报错
    EF5框架封装
    IEnumerable和IEnumerator 详解
    心宽,路自宽
  • 原文地址:https://www.cnblogs.com/huacw/p/5227500.html
Copyright © 2011-2022 走看看