mirror of
https://github.com/hs-web/hsweb-framework.git
synced 2026-09-03 06:35:25 +08:00
refactor: 雪花ID生成器发生时间回退时不拒绝生成ID
This commit is contained in:
@@ -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) {
|
||||
|
||||
@@ -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());
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user