java 有序uuid,UUID的变种-有序

为了解决UUID无序的问题,NHibernate在其主键生成方式中提供了Comb算法(combined guid/timestamp)。保留GUID的10个字节,用另6个字节表示GUID生成的时间(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);

}

用上面的算法测试一下,得到如下的结果:作为比较,前面3个是使用COMB算法得出的结果,最后12个字符串是时间序(统一毫秒生成的3个UUID),过段时间如果再次生成,则12个字符串会比图示的要大。后面3个是直接生成的GUID。

如果想把时间序放在前面,可以生成后改变12个字符串的位置,也可以修改算法类的最后两个Array.Copy。

3e7bf95b158ce574d8266842be8a928a.png

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值