美文网首页
机器码工具类-MachineUtils

机器码工具类-MachineUtils

作者: 小玉1991 | 来源:发表于2021-07-12 21:46 被阅读0次

    MachineUtils

    @Service
    @Slf4j
    public class MachineUtils {
    
        public static volatile long machineId = 0;
    
        @PostConstruct
        public void init() {
            getMachineId();
        }
    
        public static long getMachineId() {
            if (machineId == 0) {
                machineId = Math.abs((CmdUtils.getHost()+getIP()).hashCode());
                if (machineId == 0) {
                    machineId = SnowFlakeIdService.nextId();
                }
            }
            return machineId;
        }
    
        public static String getIP() {
            InetAddress address = null;
            try {
                address = InetAddress.getLocalHost();
            } catch (UnknownHostException e) {
                e.printStackTrace();
            }
            String ip = address == null ? "" : address.getHostAddress();
            log.info("getIP:{}",ip);
            return ip; //返回IP地址
        }
    }
    

    CmdUtils

    @Slf4j
    public class CmdUtils {
    
        private static String runCmd(String runCmd) {
            String cmdResult = "";
            Runtime runtimeInstance = Runtime.getRuntime();
            Process runProcess;
            try {
                runProcess = runtimeInstance.exec(runCmd);
            } catch (IOException e) {
                log.error("failed to run cmd: " + runCmd, e);
                return cmdResult;
            }
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(runProcess.getInputStream()));
            try {
                while (true) {
                    String inputLine = bufferedReader.readLine();
                    if (inputLine == null) {
                        break;
                    }
                    cmdResult += inputLine;
                }
                bufferedReader.close();
            } catch (IOException e) {
                log.error("failed to get cmd result: " + runCmd, e);
            }
            return cmdResult;
        }
    
        public static String getHost() {
            String hostname = runCmd("hostname");
            log.info("getHost:{}",hostname);
            return hostname;
        }
    }
    

    相关文章

      网友评论

          本文标题:机器码工具类-MachineUtils

          本文链接:https://www.haomeiwen.com/subject/fapdpltx.html