|
|
|
@ -32,29 +32,42 @@ namespace LINGYUN.Abp.IdGenerator.Snowflake |
|
|
|
{ |
|
|
|
var idGenerator = new SnowflakeIdGenerator(options) |
|
|
|
{ |
|
|
|
WorkerId = options.WorkerId, |
|
|
|
DatacenterId = options.DatacenterId, |
|
|
|
Sequence = options.Sequence, |
|
|
|
MaxWorkerId = -1L ^ (-1L << options.WorkerIdBits), |
|
|
|
MaxDatacenterId = -1L ^ (-1L << options.DatacenterIdBits) |
|
|
|
}; |
|
|
|
|
|
|
|
if (idGenerator.WorkerId == 0 || (int)Math.Log10(options.WorkerId) + 1 > idGenerator.MaxWorkerId) |
|
|
|
{ |
|
|
|
if (!int.TryParse(Environment.GetEnvironmentVariable("WORKERID", EnvironmentVariableTarget.Machine), out var workerId)) |
|
|
|
{ |
|
|
|
workerId = RandomHelper.GetRandom((int)idGenerator.MaxWorkerId); |
|
|
|
} |
|
|
|
|
|
|
|
if (workerId > idGenerator.MaxWorkerId || workerId < 0) |
|
|
|
{ |
|
|
|
throw new ArgumentException($"worker Id can't be greater than {idGenerator.MaxWorkerId} or less than 0"); |
|
|
|
} |
|
|
|
|
|
|
|
idGenerator.WorkerId = workerId; |
|
|
|
} |
|
|
|
|
|
|
|
if (idGenerator.DatacenterId == 0 || (int)Math.Log10(options.DatacenterId) + 1 > idGenerator.MaxDatacenterId) |
|
|
|
{ |
|
|
|
if (!int.TryParse(Environment.GetEnvironmentVariable("DATACENTERID", EnvironmentVariableTarget.Machine), out var datacenterId)) |
|
|
|
{ |
|
|
|
datacenterId = RandomHelper.GetRandom((int)idGenerator.MaxDatacenterId); |
|
|
|
} |
|
|
|
|
|
|
|
if (workerId > idGenerator.MaxWorkerId || workerId < 0) |
|
|
|
throw new ArgumentException($"worker Id can't be greater than {idGenerator.MaxWorkerId} or less than 0"); |
|
|
|
|
|
|
|
if (datacenterId > idGenerator.MaxDatacenterId || datacenterId < 0) |
|
|
|
{ |
|
|
|
throw new ArgumentException($"datacenter Id can't be greater than {idGenerator.MaxDatacenterId} or less than 0"); |
|
|
|
} |
|
|
|
|
|
|
|
idGenerator.WorkerId = workerId; |
|
|
|
idGenerator.DatacenterId = datacenterId; |
|
|
|
} |
|
|
|
|
|
|
|
return idGenerator; |
|
|
|
} |
|
|
|
@ -69,6 +82,7 @@ namespace LINGYUN.Abp.IdGenerator.Snowflake |
|
|
|
{ |
|
|
|
var timestamp = TimeGen(); |
|
|
|
|
|
|
|
// TODO: 时间回退解决方案, 保存一个时间节点, 当服务器时间发生改变, 从保存的节点开始递增
|
|
|
|
if (timestamp < _lastTimestamp) |
|
|
|
throw new Exception( |
|
|
|
$"InvalidSystemClock: Clock moved backwards, Refusing to generate id for {_lastTimestamp - timestamp} milliseconds"); |
|
|
|
|