TraceIdGenerator

public final class TraceIdGenerator {
    private static final ThreadLocal<Integer> ThreadTraceIdSequence = new ThreadLocal<Integer>();

    private static final String PROCESS_UUID;

    static {
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        PROCESS_UUID = uuid.substring(uuid.length() - 7);
    }

    private TraceIdGenerator() {
    }

    /**
     * TraceId由以下规则组成<br/>
     * 2位version号 + 1位时间戳(毫秒数) + 1位进程随机号(UUID后7位) + 1位进程数号 + 1位线程号 + 1位线程内序号
     * 
     * 注意:这里的位,是指“.”作为分隔符所占的位数,非字符串长度的位数。
     * TraceId为不定长字符串,但保证在分布式集群条件下的唯一性
     * 
     * @return
     */
    public static String generate() {
        Integer seq = ThreadTraceIdSequence.get();
        if (seq == null || seq == 10000 || seq > 10000) {
            seq = 0;
        }
        seq++;
        ThreadTraceIdSequence.set(seq);

        return Constants.SDK_VERSION 
                + "." + System.currentTimeMillis() 
                + "." + PROCESS_UUID 
                + "." + BuriedPointMachineUtil.getProcessNo()
                + "." + Thread.currentThread().getId() 
                + "." + seq;
    }
}

BuriedPointMachineUtil

public final class BuriedPointMachineUtil {
    private static String processNo;
    private static String IP;
    private static String hostName;

    static {
        processNo = getProcessNo();
    }

    public static String getProcessNo() {
        if (StringUtil.isEmpty(processNo)) {
            String name = ManagementFactory.getRuntimeMXBean().getName();
            processNo = name.split("@")[0];
        }
        return processNo;
    }

    private static InetAddress getInetAddress() {
        try {
            return InetAddress.getLocalHost();
        } catch (UnknownHostException e) {
            hostName = "unknown host!";
        }
        return null;

    }

    public static String getHostIp() {
        if (StringUtil.isEmpty(IP)) {
            InetAddress netAddress = getInetAddress();
            if (null == netAddress) {
                IP = "N/A";
            }else{
                IP = netAddress.getHostAddress(); //get the ip address
            }
        }
        return IP;
    }

    public static String getHostName() {
        if (StringUtil.isEmpty(hostName)) {
            InetAddress netAddress = getInetAddress();
            if (null == netAddress) {
                hostName = "N/A";
            }else{
                hostName = netAddress.getHostName(); //get the host address
            }
        }
        return hostName;
    }
    
    public static String getHostDesc(){
        return getHostName() + "/" + getHostIp();
    }

    private BuriedPointMachineUtil() {
        // Non
    }

}

docs


codecraft
11.9k 声望2k 粉丝

当一个代码的工匠回首往事时,不因虚度年华而悔恨,也不因碌碌无为而羞愧,这样,当他老的时候,可以很自豪告诉世人,我曾经将代码注入生命去打造互联网的浪潮之巅,那是个很疯狂的时代,我在一波波的浪潮上留下...


引用和评论

0 条评论