Пример #1
0
        private long GetTimestampAndSetSeq()
        {
            var timestamp = NumUtil.TimeMilliNum();

            if (timestamp < lastTimestamp)
            {
                //如果当前时间小于上一次ID生成的时间戳,说明系统时钟回退过这个时候应当抛出异常
                throw new ArgumentException(
                          $"Clock moved backwards.  Refusing to generate id for {lastTimestamp - timestamp} milliseconds");
            }

            // 如果是同一时间生成的,则进行毫秒内序列
            if (lastTimestamp == timestamp)
            {
                sequence = (sequence + 1) & maxSequence;

                //毫秒内序列溢出
                //阻塞到下一个毫秒,获得新的时间戳
                if (sequence == 0)
                {
                    timestamp = WaitNextMillis();
                }
            }
            //时间戳改变,毫秒内序列重置
            else
            {
                sequence = 0L;
            }

            //上次生成ID的时间截
            lastTimestamp = timestamp;
            return(timestamp);
        }
Пример #2
0
        /// <summary>
        ///  当前毫秒内序列使用完,等待下一毫秒
        /// </summary>
        /// <returns></returns>
        protected long WaitNextMillis()
        {
            long timeTicks;

            do
            {
                timeTicks = NumUtil.TimeMilliNum();
            } while (timeTicks <= lastTimestamp);
            return(timeTicks);
        }