C#版ObjectId

我希望有一个简单的方法实现分布式,解决HIS的数据库压力大的情况。而最需要有类似GUID的形式生成主键。但我拿不准纯数字ID段还是GUID一类的文本ID。最终在mongodb的obejctId的方案中得到启发,决定应用类似方案。

很高兴找到以下文章

https://www.cnblogs.com/gaochundong/archive/2013/04/24/csharp_generate_mongodb_objectid.html

ObjectId 是一个 12 Bytes 的 BSON 类型,其包含:

  1. 4 Bytes 自纪元时间开始的秒数
  2. 3 Bytes 机器描述符
  3. 2 Bytes 进程ID
  4. 3 Bytes 随机数

虽然发现文中时间部分似乎有错,但一直对于其3位byte的机器描述如何得到不知所然,以上博主给了可运行的代码真是受益非浅,在此再次感谢。

调整时间部分函数

private static byte[] GenerateTimeNowBytes()
{
    var now = DateTime.UtcNow;
    var diff = now - Epoch;//取与1970的时间差
    int timeVal = Convert.ToInt32(Math.Floor(diff.TotalSeconds));//取时间差的总秒数
    //return BitConverter.GetBytes(timeVal);//低位数在前面的字节,字符串格式化时,排序变得无序
    return GetIntBytes(timeVal, 4);
}

为了得到的ObjectId的字符串可用于实际先后的排序,所以自己写了两个数字转字节和字节转数字的方法,替换BitConverter的类似方法

private static byte[] GetIntBytes(int val, int len)
{            
    byte[] b = new byte[len]; 
    for (int i = 0; i<len; i++)
    {
        int shift = 8 * (len - 1 - i);
        b[i] = (byte)(val >> shift);
    }
    return b;
}

private static int ConvertInt32(byte[] b)
{            
    uint ival = 0;
    int len = b.Length;
    for (int i = 0; i < len; i++)
    {
        int shift = 8 * (len - 1 - i);
        ival = ival | (uint)(b[i] << shift);
    }
    return (int)ival;
}

 于是原文的生成方法修改如下

public static byte[] Generate()
{
    var oid = new byte[12];
    var copyidx = 0;
    byte[] timeByte = GenerateTimeNowBytes();
    //DateTime curTime = BytesToTime(timeByte);
    Array.Copy(timeByte, 0, oid, copyidx, 4);
    copyidx += 4;

    Array.Copy(_machineHash, 0, oid, copyidx, 3);
    copyidx += 3;

    Array.Copy(_processId, 0, oid, copyidx, 2);
    copyidx += 2;

    //byte[] cntBytes = BitConverter.GetBytes(GenerateCounter());
    byte[] cntBytes = GetIntBytes(GenerateCounter(), 3);
    Array.Copy(cntBytes, 0, oid, copyidx, 3);

    return oid;
}
View Code

 以下是mongo驱动的实现

https://github.com/mongodb/mongo-csharp-driver

https://github.com/mongodb/mongo-csharp-driver/blob/ec74978f7e827515f29cc96fba0c727828e8df7c/src/MongoDB.Bson/ObjectModel/ObjectId.cs

原文地址:https://www.cnblogs.com/kevin-Y/p/9066742.html