/// <summary> /// 雪花算法 /// </summary> /// <returns></returns> public long GenerateId() { lock (_lock) { _currentSequence++; if (_currentSequence > MaxSequence) { Thread.Sleep(1); } var timestamp = StartTime.GetTimeDiff(DateTime.Now); if (timestamp > MaxTimestamp) { throw new Exception("时间戳容量不足,请调整StartTime"); } if (timestamp < _currentTimestamp) { throw new Exception("时间获取异常,请检查服务器时间"); } else if (timestamp > _currentTimestamp) { _currentTimestamp = timestamp; _currentSequence = 0; } return(_currentTimestamp << (WorkerIdBits + SequenceBits) | WorkerId << SequenceBits | _currentSequence); } }