try {
//获取本机IP
address = InetAddress.getLocalHost();
} catch (final UnknownHostException e) {
throw new IllegalStateException(“Cannot get LocalHost InetAddress, please check your network!”,e);
}
byte[] ipAddressByteArray = address.getAddress();
//机器码一共需要10位,所以取段倒数第二个段取最后2位 + 倒数第一段全部8位
return ((ipAddressByteArray[ipAddressByteArray.length - 2] & 0B11) << Byte.SIZE) + (ipAddressByteArray[ipAddressByteArray.length - 1] & 0xFF);
- 获取下一个ID
//当前时间戳
long timestamp = System.currentTimeMillis()
//如果当前时间戳 < 最后记录时间戳 ,则可能发生时钟回拨,异常中断
if (timestamp < lastTimestamp) {
throw new RuntimeException(String.format(
“clock moved backwards. Refusing to generate id for %d milliseconds”, lastTimestamp - timestamp));
}
//如果当前时间戳 == 最后记录时间戳
if (lastTimestamp == timestamp) {
//计