dotnet-easy / easytool

A open source C# tool to make .NET easy
https://easy-dotnet.com/
MIT License
134 stars 40 forks source link

修复 生成Snowflake ID为负数的问题 #54

Open goodsxx opened 6 months ago

goodsxx commented 6 months ago

更新 IdUtil.SnowflakeId()

/// <summary>
/// 生成Snowflake ID
/// </summary>
/// <returns>生成的Snowflake ID</returns>
public static long SnowflakeId()
{
    lock (lockObj)
    {
        long timestamp = DateTime.UtcNow.Ticks - epochTicks;

        if (timestamp < lastTimestamp)
        {
            throw new Exception("时钟向后移动,拒绝生成Snowflake ID");
        }

        if (timestamp == lastTimestamp)
        {
            sequence = (sequence + 1) & sequenceMask;

            if (sequence == 0)
            {
                timestamp = NextMillis(lastTimestamp);
            }
        }
        else
        {
            sequence = 0L;
        }

        lastTimestamp = timestamp;

        return ((timestamp << (int)(workerIdBits + sequenceBits)) |
           (datacenterId << (int)sequenceBits) |
           (workerId << (int)sequenceBits) |
           sequence) & long.MaxValue; // 添加 & long.MaxValue
    }
}

修复 生成Snowflake ID为负数的问题 添加测试方法