using Yitter.IdGenerator; namespace Easy.Snowflakes; public class DriftingSnowflakeIdGenerator { private static bool _isSet = false; public static byte WorkerIdBitLength => 6; public static byte SeqBitLength => 6; public static short MaxWorkerId => (short)(Math.Pow(2.0, WorkerIdBitLength) - 1); public static short CurrentWorkerId { get; private set; } = -1; private static readonly object _locker = new(); /// /// 生成新的Id /// /// public static long Create() { if (!_isSet) throw new InvalidOperationException("please call SetIdGenerator first"); return YitIdHelper.NextId(); } /// /// 初始化Id生成器 /// /// public static void SetWorkerId(ushort workerId) { if (_isSet) throw new InvalidOperationException("allow only once"); if (workerId > MaxWorkerId || workerId < 0) throw new ArgumentException($"worker Id can't be greater than {MaxWorkerId} or less than 0"); lock (_locker) { if (_isSet) throw new InvalidOperationException("allow only once"); YitIdHelper.SetIdGenerator(new IdGeneratorOptions(workerId) { WorkerIdBitLength = WorkerIdBitLength, SeqBitLength = SeqBitLength, BaseTime = DateTime.Parse("2022-01-01 00:00:00") }); CurrentWorkerId = (short)workerId; _isSet = true; } } }