面试题:在分布式系统,你能想出来几种生成唯一ID的方案?( 五 )

/// <summary>
/// 根据GUID获取唯一数字序列
/// </summary>
public static long GuidToInt64()
{
   byte[
bytes = Guid.NewGuid().ToByteArray();
   return BitConverter.ToInt64(bytes 0);

2、为了解决UUID无序的问题 , NHibernate在其主键生成方式中提供了Comb算法(combined guid/timestamp) 。 保留GUID的10个字节 , 用另6个字节表示GUID生成的时间(DateTime) 。

/// <summary>
/// Generate a new <see cref=\"Guid\"/> using the comb algorithm.
/// </summary>
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);

推荐阅读