高並發分布式系統中生成全局唯一(訂單號)Id


1、GUID數據因毫無規律可言造成索引效率低下,影響了系統的性能,那么通過組合的方式,保留GUID的10個字節,用另6個字節表示GUID生成的時間(DateTime),這樣我們將時間信息與GUID組合起來,在保留GUID的唯一性的同時增加了有序性,以此來提高索引效率,在NHibernate中,COMB型主鍵的生成代碼如下所示:

        /// <summary>
        /// 保留GUID的10個字節,用另6個字節表示GUID生成的時間(DateTime)組合方式
        /// </summary>
        /// <returns></returns>
        public static 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);
        }

上述方法循環測試生成id如下圖

 結論:適合大型應用。即保留GUID的唯一性的同時增加了GUID有序性,提高了索引效率;解決了關聯表業務問題;生成的Id不夠友好;占據了32位。

 

2、將GUID轉為了19位數字

        /// <summary>
        /// 根據GUID獲取19位的唯一數字序列
        /// </summary>
        public static long GuidToLong()
        {
            byte[] buffer = Guid.NewGuid().ToByteArray();
            return BitConverter.ToInt64(buffer, 0);
        }

上述方法循環測試生成id如下圖

結論:適合大型應用,從業務上來說,有一個規則的編碼能體現產品的專業成度。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM