C# Guid长度雪花简单生成器的示例代码

时间:2021-05-20

标准的long雪花长度为64bit,还要浪费1bit,然后41位时间,10位workid,12位序列

guid长度128位,64位完整的时间tick,32位workid,32位序列,可谓随便用满非常豪华

也就是系统里可以根据需要有的地方存随机guid,有的地方存雪花guid,随便换

随后还有提取时间的方法,由于是64位完整时间,直接拿出来转时间就好了

这个类参考别人的代码,如果需要设计更完善的guid雪花,可以在github上或者nuget上找newid这个项目,老外写好的更完善的做法

public class GuidSnowFlakeGenerator { readonly uint _c; int _a; int _b; long _lastTick; uint _sequence; SpinLock _spinLock; public GuidSnowFlakeGenerator(uint workId) { _spinLock = new SpinLock(false); _c = workId; } public Guid Next() { var ticks = DateTime.UtcNow.Ticks; int a; int b; uint sequence; var lockTaken = false; try { _spinLock.Enter(ref lockTaken); if (ticks > _lastTick) UpdateTimestamp(ticks); else if (_sequence == uint.MaxValue) UpdateTimestamp(_lastTick + 1); sequence = _sequence++; a = _a; b = _b; } finally { if (lockTaken) _spinLock.Exit(); } var s = sequence; byte[] bytes = new byte[16]; bytes[0] = (byte)(a >> 24); bytes[1] = (byte)(a >> 16); bytes[2] = (byte)(a >> 8); bytes[3] = (byte)a; bytes[4] = (byte)(b >> 24); bytes[5] = (byte)(b >> 16); bytes[6] = (byte)(b >> 8); bytes[7] = (byte)b; bytes[8] = (byte)(_c >> 24); bytes[9] = (byte)(_c >> 16); bytes[10] = (byte)(_c >> 8); bytes[11] = (byte)(_c); bytes[12] = (byte)(s >> 24); bytes[13] = (byte)(s >> 16); bytes[14] = (byte)(s >> 8); bytes[15] = (byte)(s >> 0); return new Guid(bytes); } void UpdateTimestamp(long tick) { _b = (int)(tick & 0xFFFFFFFF); _a = (int)(tick >> 32); _sequence = 0; _lastTick = tick; } public static DateTime GetTime(Guid guid) { var bytes = guid.ToByteArray(); long tick = (long)bytes[0] << 56; tick += (long)bytes[1] << 48; tick += (long)bytes[2] << 40; tick += (long)bytes[3] << 32; tick += (long)bytes[3] << 24; tick += (long)bytes[3] << 16; tick += (long)bytes[3] << 8; tick += (long)bytes[3]; return new DateTime(tick, DateTimeKind.Utc); } }

以上就是C# Guid长度雪花简单生成器的示例代码的详细内容,更多关于c# guid雪花生成器的资料请关注其它相关文章!

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章