|
@@ -5,26 +5,27 @@ import org.slf4j.Logger;
|
|
import org.slf4j.LoggerFactory;
|
|
import org.slf4j.LoggerFactory;
|
|
|
|
|
|
import java.util.*;
|
|
import java.util.*;
|
|
|
|
+import java.util.concurrent.ThreadLocalRandom;
|
|
|
|
|
|
@Slf4j
|
|
@Slf4j
|
|
public class SnowflakeIdGenerator {
|
|
public class SnowflakeIdGenerator {
|
|
|
|
|
|
- private long workerId;
|
|
|
|
- private long dataCenterId;
|
|
|
|
|
|
+ private final long workerId;
|
|
|
|
+ private final long dataCenterId;
|
|
private long sequence = 0L;
|
|
private long sequence = 0L;
|
|
|
|
|
|
- private long twepoch = 1288834974657L;
|
|
|
|
|
|
+ private final long twepoch = 1288834974657L;
|
|
|
|
|
|
- private long workerIdBits = 5L;
|
|
|
|
- private long datacenterIdBits = 5L;
|
|
|
|
- private long maxWorkerId = -1L ^ (-1L << workerIdBits);
|
|
|
|
- private long maxDataCenterId = -1L ^ (-1L << datacenterIdBits);
|
|
|
|
- private long sequenceBits = 12L;
|
|
|
|
|
|
+ private final long workerIdBits = 5L;
|
|
|
|
+ private final long datacenterIdBits = 5L;
|
|
|
|
+ private final long maxWorkerId = ~(-1L << workerIdBits);
|
|
|
|
+ private final long maxDataCenterId = ~(-1L << datacenterIdBits);
|
|
|
|
+ private final long sequenceBits = 12L;
|
|
|
|
|
|
- private long workerIdShift = sequenceBits;
|
|
|
|
- private long datacenterIdShift = sequenceBits + workerIdBits;
|
|
|
|
- private long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits;
|
|
|
|
- private long sequenceMask = -1L ^ (-1L << sequenceBits);
|
|
|
|
|
|
+ private final long workerIdShift = sequenceBits;
|
|
|
|
+ private final long datacenterIdShift = sequenceBits + workerIdBits;
|
|
|
|
+ private final long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits;
|
|
|
|
+ private final long sequenceMask = ~(-1L << sequenceBits);
|
|
|
|
|
|
private long lastTimestamp = -1L;
|
|
private long lastTimestamp = -1L;
|
|
|
|
|
|
@@ -41,7 +42,15 @@ public class SnowflakeIdGenerator {
|
|
return generator;
|
|
return generator;
|
|
}
|
|
}
|
|
|
|
|
|
- public SnowflakeIdGenerator(long workerId, long dataCenterId) {
|
|
|
|
|
|
+ public static SnowflakeIdGenerator create(int workerId, int dataCenterId) {
|
|
|
|
+ return new SnowflakeIdGenerator(workerId, dataCenterId);
|
|
|
|
+ }
|
|
|
|
+
|
|
|
|
+ public static SnowflakeIdGenerator create() {
|
|
|
|
+ return create(ThreadLocalRandom.current().nextInt(31), ThreadLocalRandom.current().nextInt(31));
|
|
|
|
+ }
|
|
|
|
+
|
|
|
|
+ private SnowflakeIdGenerator(long workerId, long dataCenterId) {
|
|
// sanity check for workerId
|
|
// sanity check for workerId
|
|
if (workerId > maxWorkerId || workerId < 0) {
|
|
if (workerId > maxWorkerId || workerId < 0) {
|
|
throw new IllegalArgumentException(String.format("worker Id can't be greater than %d or less than 0", maxWorkerId));
|
|
throw new IllegalArgumentException(String.format("worker Id can't be greater than %d or less than 0", maxWorkerId));
|