Last active
August 2, 2018 06:52
-
-
Save rqx110/066b5ddcd5718b5883d77f129530c193 to your computer and use it in GitHub Desktop.
生成类似Mongodb的ObjectId有序、不重复Guid
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private static DateTime dt1970 = new DateTime(1970, 1, 1); | |
private static Random rnd = new Random(); | |
private static readonly int __staticMachine = ((0x00ffffff & Environment.MachineName.GetHashCode()) + | |
#if NETSTANDARD1_5 || NETSTANDARD1_6 | |
1 | |
#else | |
AppDomain.CurrentDomain.Id | |
#endif | |
) & 0x00ffffff; | |
private static readonly int __staticPid = Process.GetCurrentProcess().Id; | |
private static int __staticIncrement = rnd.Next(); | |
/// <summary> | |
/// 生成类似Mongodb的ObjectId有序、不重复Guid | |
/// </summary> | |
/// <returns></returns> | |
public static Guid NewMongodbId() { | |
var now = DateTime.Now; | |
var uninxtime = (int) now.Subtract(dt1970).TotalSeconds; | |
int increment = Interlocked.Increment(ref __staticIncrement) & 0x00ffffff; | |
var rand = rnd.Next(0, int.MaxValue); | |
var guid = $"{uninxtime.ToString("x8").PadLeft(8, '0')}{__staticMachine.ToString("x8").PadLeft(8, '0').Substring(2, 6)}{__staticPid.ToString("x8").PadLeft(8, '0').Substring(6, 2)}{increment.ToString("x8").PadLeft(8, '0')}{rand.ToString("x8").PadLeft(8, '0')}"; | |
return Guid.Parse(guid); | |
} | |
//代码来自 dotnetGen | |
//https://github.com/2881099/dotnetGen_postgresql | |
//https://github.com/2881099/dotnetGen_mysql | |
//https://github.com/2881099/dotnetGen_sqlserver |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment