账单-雪花主键-workerId-处理npe

This commit is contained in:
2025-08-29 11:41:17 +08:00
parent e3e781e093
commit b377d68e1c

View File

@@ -7,6 +7,7 @@ import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.Enumeration;
@Slf4j
public class WorkerIdUtil {
@@ -30,17 +31,45 @@ public class WorkerIdUtil {
String ip = host.getHostAddress();
byte[] mac = null;
try {
mac = NetworkInterface.getByInetAddress(host).getHardwareAddress();
NetworkInterface networkInterface = NetworkInterface.getByInetAddress(host);
if (networkInterface != null) {
mac = networkInterface.getHardwareAddress();
}
} catch (SocketException e) {
log.error("[workerId] 获取不到ip {} 的 mac地址", ip);
throw new RuntimeException(e);
}
// 如果通过InetAddress找不到MAC地址则尝试遍历网络接口
if (mac == null) {
try {
Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
while (networkInterfaces.hasMoreElements()) {
NetworkInterface networkInterface = networkInterfaces.nextElement();
if (!networkInterface.isLoopback() && networkInterface.getHardwareAddress() != null) {
mac = networkInterface.getHardwareAddress();
log.info("[workerId] 通过遍历网络接口获取到MAC地址");
break;
}
}
} catch (SocketException e) {
log.error("[workerId] 遍历网络接口获取MAC地址失败", e);
}
}
// 如果仍然找不到MAC地址则使用IP地址的哈希值
if (mac == null) {
log.warn("[workerId] 无法获取MAC地址使用IP地址哈希生成workerId");
long workerId = Math.abs(ip.hashCode()) % 32;
log.info("Generated workerId: {} from IP: {}", workerId, ip);
return workerId;
}
// 根据 MAC 或 IP 哈希生成 workerId
long workerId = Math.abs(Arrays.hashCode(mac)) % 32;
log.info("Generated workerId: {} from IP: {} MAC: {}", workerId, ip, mac);
log.info("Generated workerId: {} from IP: {} MAC: {}", workerId, ip, Arrays.toString(mac));
return workerId;
}
}