Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to solve the problem of UUID disorder

Shulou Source: shulou.com Published: 2022-06-01 23:39:47 10月04日 Update

This article mainly explains "how to solve the problem of UUID disorder". The content of the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to solve the problem of UUID disorder".

In order to solve the problem of UUID disorder, NHibernate provides Comb algorithm (combined guid/timestamp) in its primary key generation mode. Keep 10 bytes of GUID and use the other 6 bytes to represent the time when the GUID was generated (DateTime).

/ Generate a new using the comb algorithm. / / private Guid GenerateComb () {byte [] guidArray = Guid.NewGuid () .ToByteArray (); DateTime baseDate = new DateTime (1900, 1,1); DateTime now = DateTime.Now; / / Get the days and milliseconds which will be used to build / / the byte string TimeSpan days = new TimeSpan (now.Ticks-baseDate.Ticks); TimeSpan msecs = now.TimeOfDay / / Convert to a byte array / / Note that SQL Server is accurate to 1/300th of a / / millisecond so we divide by 3.333333 byte [] daysArray = BitConverter.GetBytes (days.Days); byte [] msecsArray = BitConverter.GetBytes ((long) (msecs.TotalMilliseconds / 3.333333)); / / Reverse the bytes to match SQL Servers ordering Array.Reverse (daysArray); Array.Reverse (msecsArray) / / Copy the bytes into the guid Array.Copy (daysArray, daysArray.Length-2, guidArray, guidArray.Length-6,2); Array.Copy (msecsArray, msecsArray.Length-4, guidArray, guidArray.Length-4,4); return new Guid (guidArray);}

Test it with the above algorithm and get the following results: for comparison, the first three are the results of using the COMB algorithm, and the last 12 strings are time series (3 UUID generated in uniform milliseconds). If you generate them again over time, the 12 strings will be larger than the figure. The last three are directly generated GUID.

If you want to put the timing first, you can change the position of 12 strings after generation, or you can modify the last two Array.Copy of the algorithm class.

Thank you for reading, the above is the content of "how to solve the problem of UUID disorder". After the study of this article, I believe you have a deeper understanding of how to solve the problem of UUID disorder, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Tags: Problem generation time algorithm character learning content string byte result two position again that is idea situation article way more knowledge Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MariaDB Xiaomi macOS Shulou Technology Docker