update - 调整下基于时间 ID 的生成器
This commit is contained in:
parent
ffd127bf4b
commit
2ffa124240
@ -17,20 +17,19 @@ public class TimeBasedIdGenerator implements IdGenerator {
|
||||
|
||||
private static final long SEQUENCE_BITS = 9L;
|
||||
private static final long MAX_SEQUENCE = ~(-1L << SEQUENCE_BITS);
|
||||
|
||||
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmm");
|
||||
private static final AtomicLong sequence = new AtomicLong(0);
|
||||
private static volatile String lastTimestamp = "";
|
||||
|
||||
@Override
|
||||
public synchronized String getNextId() {
|
||||
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmm");
|
||||
String timestamp = dateFormat.format(new Date());
|
||||
|
||||
if (timestamp.equals(lastTimestamp)) {
|
||||
long currentSequence = sequence.incrementAndGet() & MAX_SEQUENCE;
|
||||
if (currentSequence == 0) {
|
||||
// 如果递增数已达到最大值,则等待下一毫秒
|
||||
timestamp = tilNextTimestamp(timestamp);
|
||||
timestamp = tilNextTimestamp(timestamp, dateFormat);
|
||||
}
|
||||
} else {
|
||||
sequence.set(0);
|
||||
@ -41,7 +40,7 @@ public class TimeBasedIdGenerator implements IdGenerator {
|
||||
return timestamp + String.format("%09d", sequence.get());
|
||||
}
|
||||
|
||||
private String tilNextTimestamp(String lastTimestamp) {
|
||||
private String tilNextTimestamp(String lastTimestamp, SimpleDateFormat dateFormat) {
|
||||
String timestamp = dateFormat.format(new Date());
|
||||
while (timestamp.equals(lastTimestamp)) {
|
||||
timestamp = dateFormat.format(new Date());
|
||||
|
||||
Loading…
Reference in New Issue
Block a user