refactor: 雪花ID生成器发生时间回退时不拒绝生成ID

This commit is contained in:
zhouhao
2024-12-02 18:14:22 +08:00
parent 8801a1e16b
commit 988feffcf2
2 changed files with 40 additions and 4 deletions

View File

@@ -51,7 +51,7 @@ public class SnowflakeIdGenerator {
return create(ThreadLocalRandom.current().nextInt(31), ThreadLocalRandom.current().nextInt(31));
}
private SnowflakeIdGenerator(long workerId, long dataCenterId) {
public SnowflakeIdGenerator(long workerId, long dataCenterId) {
// sanity check for workerId
if (workerId > maxWorkerId || workerId < 0) {
throw new IllegalArgumentException(String.format("worker Id can't be greater than %d or less than 0", maxWorkerId));
@@ -66,10 +66,11 @@ public class SnowflakeIdGenerator {
public synchronized long nextId() {
long timestamp = timeGen();
//时间回退
if (timestamp < lastTimestamp) {
log.error("clock is moving backwards. Rejecting requests until {}.", lastTimestamp);
throw new UnsupportedOperationException(String.format("Clock moved backwards. Refusing to generate id for %d milliseconds", lastTimestamp - timestamp));
//发生回退时不拒绝,有可能出现重复数据?
log.warn("clock is moving backwards {}.", lastTimestamp);
// throw new UnsupportedOperationException(String.format("Clock moved backwards. Refusing to generate id for %d milliseconds", lastTimestamp - timestamp));
}
if (lastTimestamp == timestamp) {

View File

@@ -0,0 +1,35 @@
package org.hswebframework.web.id;
import org.junit.Test;
import java.util.concurrent.atomic.AtomicLong;
import static org.junit.Assert.*;
public class SnowflakeIdGeneratorTest {
@Test
public void test(){
AtomicLong time = new AtomicLong(System.currentTimeMillis());
SnowflakeIdGenerator generator = new SnowflakeIdGenerator(0,1){
@Override
protected long timeGen() {
return time.get();
}
};
System.out.println(generator.nextId());
//回退1秒
time.addAndGet(-1000);
System.out.println(generator.nextId());
time.addAndGet(2000);
System.out.println(generator.nextId());
}
}