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

59 lines
1.6 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

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; // 机器码,可以自定义
static object o = new object();
public static long Generate()
{
lock (o)
{
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;
}
}
}