
cn.micro.core.util.TraceIdUtil Maven / Gradle / Ivy
package cn.micro.core.util;
import cn.micro.core.context.CurrentContext;
import java.util.concurrent.atomic.AtomicInteger;
import static cn.micro.core.constant.Cants.*;
/**
* ...
*/
public final class TraceIdUtil {
private static String IP_16 = "ffffffff";
static {
try {
String ipAddress = INetUtil.getHostIp();
if (ipAddress != null) {
IP_16 = getIP_16(ipAddress);
}
} catch (Throwable e) {
/*
* empty catch block
*/
}
}
private static final AtomicInteger atomicInteger = new AtomicInteger(999);
private static int getNextId() {
for (; ; ) {
int current = atomicInteger.get();
int next = (current > 8999) ? 1000 : current + 1;
if (atomicInteger.compareAndSet(current, next)) {
return next;
}
}
}
private static String getIP_16(String ip) {
String[] ips = ip.split("\\.");
StringBuilder sb = new StringBuilder();
for (String column : ips) {
String hex = Integer.toHexString(Integer.parseInt(column));
if (hex.length() == 1) {
sb.append('0').append(hex);
} else {
sb.append(hex);
}
}
return sb.toString();
}
public static String genTraceId() {
return IP_16 + System.currentTimeMillis() + getNextId() + RuntimeUtil.getPId() + SPLIT_POINT + ZERO;
}
public static String genNextTraceId(String traceId) {
AtomicInteger integer = CurrentContext.get(traceId);
if (null == integer) {
return traceId;
}
int val = integer.addAndGet(1);
return traceId + SPLIT_POINT + val;
}
public static String currentTraceId() {
return CurrentContext.get(CURRENT_TRACE_ID);
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy