Browse Source

[Bug][SnowFlakeUtils] fix snowFlake bug (#6744)

* fix snowFlake bug

* fix hash machine
3.0.0/version-upgrade
JinYong Li 3 years ago committed by GitHub
parent
commit
be28d2c63b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 10
      dolphinscheduler-common/src/main/java/org/apache/dolphinscheduler/common/utils/SnowFlakeUtils.java
  2. 3
      dolphinscheduler-common/src/test/java/org/apache/dolphinscheduler/common/utils/SnowFlakeUtilsTest.java

10
dolphinscheduler-common/src/main/java/org/apache/dolphinscheduler/common/utils/SnowFlakeUtils.java

@ -24,13 +24,13 @@ import java.util.Objects;
public class SnowFlakeUtils {
// start timestamp
private static final long START_TIMESTAMP = 1609430400000L; //2021-01-01 00:00:00
// Number of digits
private static final long SEQUENCE_BIT = 13;
// Each machine generates 32 in the same millisecond
private static final long SEQUENCE_BIT = 5;
private static final long MACHINE_BIT = 2;
private static final long MAX_SEQUENCE = ~(-1L << SEQUENCE_BIT);
// The displacement to the left
private static final long MACHINE_LEFT = SEQUENCE_BIT;
private static final long TIMESTAMP_LEFT = SEQUENCE_BIT + MACHINE_BIT;
private static final long MACHINE_LEFT = SEQUENCE_BIT + MACHINE_BIT;
private static final long TIMESTAMP_LEFT = SEQUENCE_BIT + MACHINE_BIT + MACHINE_LEFT;
private final int machineId;
private long sequence = 0L;
private long lastTimestamp = -1L;
@ -40,7 +40,7 @@ public class SnowFlakeUtils {
private SnowFlakeUtils() throws SnowFlakeException {
try {
this.machineId = Math.abs(Objects.hash(InetAddress.getLocalHost().getHostName())) % 32;
this.machineId = Math.abs(Objects.hash(InetAddress.getLocalHost().getHostName())) % 4;
} catch (UnknownHostException e) {
throw new SnowFlakeException(e.getMessage());
}

3
dolphinscheduler-common/src/test/java/org/apache/dolphinscheduler/common/utils/SnowFlakeUtilsTest.java

@ -23,7 +23,8 @@ public class SnowFlakeUtilsTest {
@Test
public void testNextId() {
try {
for (int i = 0; i < 5; i++) {
for (int i = 0; i < 100; i++) {
Thread.sleep(1);
System.out.println(SnowFlakeUtils.getInstance().nextId());
}
} catch (Exception e) {

Loading…
Cancel
Save