HAARFTE/Assets/DemoGame/GameScript/Hotfix/FloorBase/IDGenerator.cs

54 lines
1.5 KiB
C#
Raw Normal View History

2024-10-24 16:16:57 +08:00
using System;
namespace ZC
{
/// <summary>
/// id生成器当前使用的是时间戳作为id生成器的唯一id
/// </summary>
public static class IDGenerator
{
//
private static long lastTimestamp = -1L;
private static long sequence = 0L;
private static readonly long twepoch = 1288834974657L; // Twitter Snowflake算法中的自定义起始时间
private static readonly long machineId = 1L; // 机器码,可以自定义
public static long Generate()
{
long timestamp = TimeGen();
if (lastTimestamp == timestamp)
{
sequence = (sequence + 1) & 4095L;
if (sequence == 0)
{
timestamp = TilNextMillis(lastTimestamp);
}
}
else
{
sequence = 0L;
}
lastTimestamp = timestamp;
return (timestamp - twepoch) << 22 | machineId << 12 | sequence;
}
private static long TilNextMillis(long lastTimestamp)
{
long timestamp = TimeGen();
while (timestamp <= lastTimestamp)
{
timestamp = TimeGen();
}
return timestamp;
}
private static long TimeGen()
{
return (long)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds;
}
}
}