我有一个特定要求,需要生成当天的唯一序列号。即使 JVM 重新启动,该实用程序也应该能够生成不重复的序列。
先决条件:
- 不应使用数据库序列。
- 不应在文件系统中存储任何内容。
- 该序列可以全天重复。
- 序列不应在一天内重复,即使 JVM 重新启动(这已通过不同的属性确保)。
- 每秒的序列数最低要求为 99。
Sequence format: ######## (8 digits max)
注意:这将在不同的节点实例中运行,因此序列的第一个数字被保留用于标识节点。
最佳答案
一个简单的基于时钟的解决方案可能如下所示:
static int seq(int nodeId) {
int val = nodeId * 100_000_000 + (int) (System.currentTimeMillis() % 100_000_000);
try {
Thread.sleep(1); // introduce delay to ensure the generated values are unique
} catch (InterruptedException e) {}
return val;
}
延迟可以另外随机化(最多 5 毫秒):
static Random random = new SecureRandom();
static int seq(int nodeId) {
int val = nodeId * 100_000_000 + (int) (System.currentTimeMillis() % 100_000_000);
try {
Thread.sleep(1 + random.nextInt(4));
} catch (InterruptedException e) {}
return val;
}
关于Java序列生成不重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64603669/