Java:唯一的10位ID [英] Java: Unique 10 digit ID
问题描述
我需要在Java中生成一个唯一的10位数ID。以下是此ID的限制:
I need to generate a unique 10 digit ID in Java. These are the restrictions for this ID:
- 仅数字
- 最多10位数
- 每秒最多可创建10个不同的ID
- 必须是唯一的(即使应用程序重新启动)
- 无法在数据库中保存数字
- 尽可能快地不向系统添加太多的延迟
- Only Numeric
- Maximum 10 digits
- Possible to create up to 10 different IDs per second
- Has to be unique (even if the application re-starts)
- Not possible to save a number in the Database
- As fast as possible NOT to add much lattency to the system
我到目前为止找到的最佳解决方案如下:
The best solution I found so far is the following:
private static int inc = 0;
private static long getId(){
long id = Long.parseLong(String.valueOf(System.currentTimeMillis())
.substring(1,10)
.concat(String.valueOf(inc)));
inc = (inc+1)%10;
return id;
}
此解决方案存在以下问题:
This solution has the following problems:
- 如果出于任何原因需要每秒创建10个以上的ID,此解决方案将无效。
- 关于32年这个ID可以重复(这可能是可以接受的)
创建此ID的任何其他解决方案?
Any other solution to create this ID?
我还没有想过与我有任何其他问题?
Any other problem I haven't thought of with mine?
感谢您的帮助,
推荐答案
这是对你的一个小小的改进,但应具有弹性。
This is a small enhancement to yours but should be resilient.
private static final long LIMIT = 10000000000L;
private static long last = 0;
public static long getID() {
// 10 digits.
long id = System.currentTimeMillis() % LIMIT;
if ( id <= last ) {
id = (last + 1) % LIMIT;
}
return last = id;
}
因为它应该以每秒1000次的速度管理,周期相对较短率。要扩展循环速率(但缩短分辨率),可以使用(System.currentTimeMillis()/ 10)%10000000000L
或(System.currentTimeMillis( )/ 100)%10000000000L
。
As it is it should manage up to 1000 per second with a comparatively short cycle rate. To extend the cycle rate (but shorten the resolution) you could use (System.currentTimeMillis() / 10) % 10000000000L
or (System.currentTimeMillis() / 100) % 10000000000L
.
这篇关于Java:唯一的10位ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!