You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

55 lines
1.6 KiB

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();
/// <summary>
/// 生成新的Id
/// </summary>
/// <returns></returns>
public static long Create()
{
if (!_isSet)
throw new InvalidOperationException("please call SetIdGenerator first");
return YitIdHelper.NextId();
}
/// <summary>
/// 初始化Id生成器
/// </summary>
/// <param name="workerId"></param>
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;
}
}
}