@SneakyThrows private boolean waitTolerateTimeDifferenceIfNeed(final long currentMilliseconds) { if (lastMilliseconds <= currentMilliseconds) { return false; } long timeDifferenceMilliseconds = lastMilliseconds - currentMilliseconds; Preconditions.checkState(timeDifferenceMilliseconds < getMaxTolerateTimeDifferenceMilliseconds(), "Clock is moving backwards, last time is %d milliseconds, current time is %d milliseconds", lastMilliseconds, currentMilliseconds); Thread.sleep(timeDifferenceMilliseconds); return true; }
private long getWorkerId() { long result = Long.valueOf(properties.getProperty("worker.id", String.valueOf(WORKER_ID))); if (result <= 0L){ result = generateWorkerId(); } Preconditions.checkArgument(result >= 0L && result < WORKER_ID_MAX_VALUE); return result; }
private int getMaxVibrationOffset() { int result = Integer.parseInt(properties.getProperty("max.vibration.offset", String.valueOf(DEFAULT_VIBRATION_VALUE))); Preconditions.checkArgument(result >= 0 && result <= SEQUENCE_MASK, "Illegal max vibration offset"); return result; }
private int getMaxTolerateTimeDifferenceMilliseconds() { return Integer.valueOf(properties.getProperty("max.tolerate.time.difference.milliseconds", String.valueOf(MAX_TOLERATE_TIME_DIFFERENCE_MILLISECONDS))); }
private long waitUntilNextTime(final long lastTime) { long result = timeService.getCurrentMillis(); while (result <= lastTime) { result = timeService.getCurrentMillis(); } return result; }
private long generateWorkerId() { try { return generateWorkerIdBaseOnMac(); } catch (Exception e) { return generateRandomWorkerId(); } } /** * randomly generate one as workerId * @return workerId */ private long generateRandomWorkerId() { return new Random().nextInt((int)WORKER_ID_MAX_VALUE + 1); } /** * use lowest 10 bit of available MAC as workerId * @return workerId * @throws Exception when there is no available mac found */ private long generateWorkerIdBaseOnMac() throws Exception { Enumeration<NetworkInterface> all = NetworkInterface.getNetworkInterfaces(); while (all.hasMoreElements()) { NetworkInterface networkInterface = all.nextElement(); boolean loopBack = networkInterface.isLoopback(); boolean isVirtual = networkInterface.isVirtual(); if (loopBack || isVirtual) { continue; } byte[] mac = networkInterface.getHardwareAddress(); return ((mac[4] & 0B11) << 8) | (mac[5] & 0xFF); } throw new RuntimeException("no available mac found"); } /** * 获取随机ID * @return 随机ID用以替代传统的UUID */ public String get32UUID() { ThreadLocalRandom random = ThreadLocalRandom.current(); return (new UUID(random.nextLong(), random.nextLong())).toString().replace("-", ""); }
}
1 2 3 4 5
public class TimeService { public long getCurrentMillis() { return System.currentTimeMillis(); } }
配置文件
1 2 3 4 5 6 7 8 9 10 11 12 13
@SpringBootConfiguration public class IdAutoConfiguration { /** * 注入ID生成器实现 * @return see {@link DefaultIdGenerator} */ @Bean @ConditionalOnMissingBean public IdGenerator idGenerator() { return new DefaultIdGenerator(); } }