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;
}
}
网友评论