Abp Guid是连续如何实现的
起因
最近一直在学习Abp框架相关的知识,在Abp文档上看到通过IGuidGenerator接口Create方法实现的GUID是连续的.便想看看内部是如何实现的.Create源码(裁剪部分代码)
var random = RandomNumberGenerator.Create();
var randomBytes = new byte[10];
random.GetBytes(randomBytes);
long timestamp = DateTime.UtcNow.Ticks / 10000L;
// Then get the bytes
byte[] timestampBytes = BitConverter.GetBytes(timestamp);
// Since we're converting from an Int64, we have to reverse on
// little-endian systems.
if (BitConverter.IsLittleEndian) //判断是否为小端
{
//这涉及到cpu机构 x86为小端 arm支持大端序和小端序
Array.Reverse(timestampBytes);
}
byte[] guidBytes = new byte[16];
//通过Buffer.BlockCopy进行内容拷贝,性能更好,内部是使用Memmove
//将数组转为指针,进行相关内容进行拷贝的
Buffer.BlockCopy(randomBytes, 0, guidBytes, 0, 10);
Buffer.BlockCopy(timestampBytes, 2, guidBytes, 10, 6);
var guid = new Guid(guidBytes);
Console.WriteLine(guid.ToString());
看到上面的代码,可以简单的分为一下几个步骤:
1. 创建一个长度为10的byte数组,存放随机数.
2. 获取当前时间的毫秒数
3. 判断是否为小端,如果为小端,则把时间的毫秒数进行反转
4. 创建长度为16的byte,将随机数拷贝该数组,然后将时间毫秒数也拷贝到该数组中
5. 通过Guid的构造函数,传入长度16的数组,进行生成连续的Guid
秋风
2021-03-28