生成唯一ID的公式? [英] Formulas to generate a unique id?

查看:134
本文介绍了生成唯一ID的公式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在不使用GUID的情况下获得有关生成唯一ID的一些想法.最好,我希望唯一值的类型为int32.

我正在寻找可以用于数据库主键以及对URL友好的东西.

这些可以被认为是独特的吗?

  1. (int)DateTime.Now.Ticks
  2. (int)DateTime.Now * RandomNumber

还有其他想法吗?

谢谢

好吧,我正在尝试实践域驱动设计,并且我的所有实体在创建时都需要具有一个ID才有效.从理论上讲,我可以打电话给数据库以获取一个自动递增的数字,但是当数据库相关的内容进入域时,我宁愿避开这个问题.

解决方案

这取决于您需要它的独特性以及需要给ID提供多少项.您最好的选择是按顺序分配它们;如果您想花哨的话,很可能会遇到生日悖论"(发生冲突的可能性比您预期的要大),或者(如在您的案例1中所述)被强制限制了发行它们的速度.

在大多数情况下,您的上述1)比2)更好;它的速率是有限的-您每次发出的价格不能超过1个ID-但不容易受到生日悖论"的影响.您的2)只是丢掉了一点.使用随机数进行XOR运算可能会更好,但是无论如何我都不认为rand会给您买任何东西,只是隐藏了问题&使其难以修复.

I would like to get a few ideas on generating unique id's without using the GUID. Preferably i would like the unique value to be of type int32.

I'm looking for something that can be used for database primary key as well as being url friendly.

Can these considered Unique?

  1. (int)DateTime.Now.Ticks
  2. (int)DateTime.Now * RandomNumber

Any other ideas?

Thanks

EDIT: Well i am trying to practise Domain Driven Design and all my entities need to have a ID upon creation to be valid. I could in theory call into the DB to get an auto incremented number but would rather steer clear of this as DB related stuff is getting into the Domain.

解决方案

It depends on how unique you needed it to be and how many items you need to give IDs to. Your best bet may be assigning them sequentially; if you try to get fancy you'll likely run into the Birthday Paradox (collisions are more likely than you might expect) or (as in your case 1) above) be foreced to limit the rate at which you can issue them.

Your 1) above is a little better than the 2) for most cases; it's rate limited--you can't issue more than 1 ID per tick--but not susceptible to the Birthday Paradox. Your 2) is just throwing bits away. Might be slightly better to XOR with the random number, but in any case I don't think the rand is buying you anything, just hiding the problem & making it harder to fix.

这篇关于生成唯一ID的公式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆