全局唯一编码ID生成器
package com.util;
import java.lang.management.ManagementFactory;
import java.net.NetworkInterface;
import java.nio.BufferUnderflowException;
import java.nio.ByteBuffer;
import java.security.SecureRandom;
import java.util.Enumeration;
import org.apache.commons.lang3.time.DateFormatUtils;
public class GeneratorId {
public static void main(String[] args) {
long a = System.currentTimeMillis();
for (int i = 0; i < 100; i++) {
System.out.println(nextFormatId());
nextFormatId();
}
System.out.println(System.currentTimeMillis() - a);
System.out.println(nextMillisId());
}
private static final long MIN_SEQUENCE = 10000L;
private static final long MAX_SEQUENCE = 99999L;
private static long sequence = MIN_SEQUENCE;
private static final String MP;
static {
try {
int machineIdentifier = createMachineIdentifier();
int processIdentifier = createProcessIdentifier();
int hashcode = (machineIdentifier + "" + processIdentifier).hashCode();
String mp = "";
if (hashcode != Integer.MIN_VALUE) {
mp = Integer.toString(Math.abs(hashcode));
} else {
mp = Integer.toString(Integer.MIN_VALUE);
}
MP = mp;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private GeneratorId() {
}
public static synchronized String nextFormatId() {
return DateFormatUtils.format(System.currentTimeMillis(), "yyyyMMddHHmmssSSS") + MP
+ nextSequence();
}
private static synchronized String nextMillisId() {
return System.currentTimeMillis() + MP + nextSequence();
}
private static synchronized long nextSequence() {
if (sequence >= MAX_SEQUENCE) {
sequence = MIN_SEQUENCE;
}
++sequence;
return sequence;
}
private static int createMachineIdentifier() {
int machinePiece;
try {
StringBuilder stringBuilder = new StringBuilder();
Enumeration<NetworkInterface> networkInterfaces = NetworkInterface
.getNetworkInterfaces();
while (networkInterfaces.hasMoreElements()) {
NetworkInterface networkInterface = networkInterfaces.nextElement();
stringBuilder.append(networkInterface.toString());
byte[] mac = networkInterface.getHardwareAddress();
if (mac != null) {
ByteBuffer byteBuffer = ByteBuffer.wrap(mac);
try {
stringBuilder.append(byteBuffer.getChar());
stringBuilder.append(byteBuffer.getChar());
stringBuilder.append(byteBuffer.getChar());
} catch (BufferUnderflowException shortHardwareAddressException) {
}
}
}
machinePiece = stringBuilder.toString().hashCode();
} catch (Throwable t) {
machinePiece = new SecureRandom().nextInt();
}
return machinePiece;
}
private static int createProcessIdentifier() {
int processId;
try {
String processName = ManagementFactory.getRuntimeMXBean().getName();
if (processName.contains("@")) {
processId = Integer.parseInt(processName.substring(0, processName.indexOf('@')));
} else {
processId = processName.hashCode();
}
} catch (Throwable t) {
processId = new SecureRandom().nextInt();
}
return processId;
}
}