您好,欢迎来到12图资源库!分享精神,快乐你我!我们只是素材的搬运工!!
  • 首 页
  • 当前位置:首页 > 开发 > WEB开发 >
    了解Snowflake算法的完成原理(8)
    时间:2020-08-10 21:30 来源:网络整理 作者:网络 浏览:收藏 挑错 推荐 打印

                throw new IllegalArgumentException("Worker id must be in [0,31]"); 

            } 

            if (!(MIN_DC_ID <= dataCenterId && dataCenterId <= MAX_DC_ID)) { 

                throw new IllegalArgumentException("Data center id must be in [0,31]"); 

            } 

        } 

     

        @Override 

        public synchronized long generate() { 

            long timestamp = System.currentTimeMillis(); 

            // 时钟回拨 

            if (timestamp < lastTimestamp) { 

                throw new IllegalStateException("Clock moved backwards"); 

            } 

            // 同一毫秒内并发 

            if (lastTimestamp == timestamp) { 

                sequence = sequence + 1; 

                if (sequence == MAX_SEQUENCE) { 

                    timestamp = untilNextMillis(lastTimestamp); 

                    sequence = 0L; 

                } 

            } else { 

                // 下一毫秒重置sequence为0 

                sequence = 0L; 

            } 

            lastTimestamp = timestamp

            // 41位时间戳字符串,不够位数左边补"0" 

            String timestampString = leftPadding(Long.toBinaryString(timestamp - epoch), 41); 

            // 5位机器ID字符串,不够位数左边补"0" 

            String workerIdString = leftPadding(Long.toBinaryString(workerId), 5); 

            // 5位数据中心ID字符串,不够位数左边补"0" 

            String dataCenterIdString = leftPadding(Long.toBinaryString(dataCenterId), 5); 

            // 12位序列号字符串,不够位数左边补"0" 

            String seqString = leftPadding(Long.toBinaryString(sequence), 12); 

    (责任编辑:admin)