注意一点如果是分布式集群等环境,需要区分机器码,不然在大量并发可能会重复。如果是单机,直接用就行
package org.com.utils;
import org.apache.ibatis.logging.LogException;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Date;
import java.util.Enumeration;
import java.util.Random;
import java.util.UUID;
public class IdUtils {
/**
* 获取本机ip
* @return
*/
private static String getHostIp(){
try{
Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
while (allNetInterfaces.hasMoreElements()){
NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
while (addresses.hasMoreElements()){
InetAddress ip = (InetAddress) addresses.nextElement();
if (ip != null
&& ip instanceof Inet4Address
&& !ip.isLoopbackAddress() //loopback地址即本机地址,IPv4的loopback范围是127.0.0.0 ~ 127.255.255.255
&& ip.getHostAddress().indexOf(":")==-1){
System.out.println("本机的IP = " + ip.getHostAddress());
return ip.getHostAddress();
}
}
}
}catch(Exception e){
e.printStackTrace();
}
return null;
}
private static String createMachineNumberUUId() {
int machineId = 1;//最大支持1-9个集群机器部署
int hashCodeV = UUID.randomUUID().toString().hashCode();
if(hashCodeV < 0) {//有可能是负数
has

博客指出在分布式集群等环境下使用时,需区分机器码,否则大量并发可能出现重复情况;而在单机环境下可直接使用,强调了不同环境使用的差异。
最低0.47元/天 解锁文章
996

被折叠的 条评论
为什么被折叠?



