【发布时间】:2022-01-04 07:20:51
【问题描述】:
我有一个要求,我们需要生成 11 个字符的唯一块 ID。
我们有以下逻辑来生成它,
public String generateBlockId(){
boolean alreadyExists = true;
String newBlockId = "";
while(alreadyExists) {
newBlockId = generateYYDDDSSSSSString();
Allocation allocation = repo.findTopByBlockId(newBlockId);
if(allocation == null) {
blockIdAlreadyExists = false;
}
}
return newBlockId;
}
public String generateYYDDDSSSSSString() {
String dateString;
LocalDateTime now = LocalDateTime.now();
Integer year = now.getYear() % 100;
Integer day = now.getDayOfYear();
Integer second = now.toLocalTime().toSecondOfDay();
String YY = StringUtils.leftPad(year.toString(), 2, "0");
String DDD = StringUtils.leftPad(day.toString(), 3, "0");
String SSSSSS = StringUtils.leftPad(second.toString(), 6, "0");
dateString = YY + DDD + SSSSSS;
return dateString;
}
我们一次最多有 100 个并发用户,当生成的 id 存储到数据库时,它会影响性能并导致唯一约束异常。
有没有更好的办法解决这个问题。
注意:业务要求只有11位数字。
【问题讨论】:
-
嗯,时间戳很少是唯一的,因此有可能 2 个用户在同一秒内生成 id。为什么不在代码或数据库中使用简单的序列生成器来处理这个问题?
-
@Thomas。这只有11个字符,所以以后有可能会乱序!
-
当然,但无论您如何生成这些数字,最终都会出现乱序。一个 11 位数字允许多达 1 万亿个唯一 ID,因此如果您担心您的应用程序会使用更多,那么使用秒精度的时间戳会更加冒险。
标签: java oracle unique-constraint unique-key