根据时间戳 生成全局唯一id
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
public class IdGenerator {
private static long workerId;
private static long dataCenterId;
private static long sequence;
private static long startTimestamp = 1288834974657L;
private static long workerIdBits = 5L;
private static long dataCenterIdBits = 5L;
private static long maxWorkerId = -1L ^ (-1L << workerIdBits);
private static long maxDataCenterId = -1L ^ (-1L << dataCenterIdBits);
private static long sequenceBits = 12L;
private static long sequenceMask = -1L ^ (-1L << sequenceBits);
private static long workerIdShift = sequenceBits;
private static long dataCenterIdShift = sequenceBits + workerIdBits;
private static long timestampLeftShift = sequenceBits + workerIdBits + dataCenterIdBits;
private static long lastTimestamp = -1L;
public IdGenerator() {
this.workerId = getMachineNum() & maxWorkerId;
this.dataCenterId = getMachineNum() & maxDataCenterId;
this.sequence = 0L;
}
private static long getMachineNum() {
long machinePiece;
StringBuilder sb = new StringBuilder();
Enumeration<NetworkInterface> e = null;
try {
e = NetworkInterface.getNetworkInterfaces();
} catch (SocketException e1) {
e1.printStackTrace();
}
while (e.hasMoreElements()) {
NetworkInterface ni = e.nextElement();
sb.append(ni.toString());
}
machinePiece = sb.toString().hashCode();
return machinePiece;
}
public synchronized static long nextId() {
long timestamp = timeGen();
if (timestamp < lastTimestamp) {
throw new RuntimeException(String.format("Clock moved backwards. Refusing to generate id for %d milliseconds", lastTimestamp - timestamp));
}
if (lastTimestamp == timestamp) {
sequence = (sequence + 1) & sequenceMask;
if (sequence == 0) {
timestamp = tilNextMillis(lastTimestamp);
}
} else {
sequence = 0;
}
lastTimestamp = timestamp;
return ((timestamp - startTimestamp) << timestampLeftShift) |
(dataCenterId << dataCenterIdShift) |
(workerId << workerIdShift) |
sequence;
}
private static long tilNextMillis(long lastTimestamp) {
long timestamp = timeGen();
while (timestamp <= lastTimestamp) {
timestamp = timeGen();
}
return timestamp;
}
private static long timeGen() {
return System.currentTimeMillis();
}
}