SnowWorkerM2.cs 1.7 KB
Newer Older
Z
zhouzj 已提交
1 2
/*
 * 版权属于:yitter(yitter@126.com)
yitter's avatar
yitter 已提交
3
 * 开源地址:https://github.com/yitter/idgenerator
Z
zhouzj 已提交
4 5 6 7 8 9 10
 * 版权协议:MIT
 * 版权说明:只要保留本版权,你可以免费使用、修改、分发本代码。
 * 免责条款:任何因为本代码产生的系统、法律、政治、宗教问题,均与版权所有者无关。
 * 
 */

using System;
Z
init  
zhouzj 已提交
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
using System.Collections.Generic;
using System.Text;

namespace Yitter.IdGenerator
{
    /// <summary>
    /// 常规雪花算法
    /// </summary>
    internal class SnowWorkerM2 : SnowWorkerM1
    {
        public SnowWorkerM2(IdGeneratorOptions options) : base(options)
        {

        }

        public override long NextId()
        {
            lock (_SyncLock)
            {
                long currentTimeTick = GetCurrentTimeTick();

                if (_LastTimeTick == currentTimeTick)
                {
                    if (_CurrentSeqNumber++ > MaxSeqNumber)
                    {
                        _CurrentSeqNumber = MinSeqNumber;
                        currentTimeTick = GetNextTimeTick();
                    }
                }
                else
                {
                    _CurrentSeqNumber = MinSeqNumber;
                }

                if (currentTimeTick < _LastTimeTick)
                {
                    throw new Exception(string.Format("Time error for {0} milliseconds", _LastTimeTick - currentTimeTick));
                }

                _LastTimeTick = currentTimeTick;
                var result = ((currentTimeTick << _TimestampShift) + ((long)WorkerId << SeqBitLength) + (uint)_CurrentSeqNumber);

                return result;
            }
        }

    }
}