当前位置 : 主页 > 网络编程 > c#编程 >

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

来源:互联网 收集:自由互联 发布时间:2021-05-09
标准的long雪花长度为64bit,还要浪费1bit,然后41位时间,10位workid,12位序列 guid长度128位,64位完整的时间tick,32位workid,32位序列,可谓随便用满非常豪华 也就是系统里可以根据需要

标准的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雪花生成器的资料请关注自由互联其它相关文章!

网友评论