账单-雪花主键-发mq前预生产分布式序列id
This commit is contained in:
@@ -7,7 +7,6 @@ import java.net.NetworkInterface;
|
||||
import java.net.SocketException;
|
||||
import java.net.UnknownHostException;
|
||||
import java.util.Arrays;
|
||||
import java.util.Enumeration;
|
||||
|
||||
@Slf4j
|
||||
public class WorkerIdUtil {
|
||||
@@ -15,7 +14,8 @@ public class WorkerIdUtil {
|
||||
public static long generateDataCenterId() {
|
||||
InetAddress host = null;
|
||||
String ip = null;
|
||||
|
||||
byte[] mac = null;
|
||||
|
||||
// 优先使用Docker环境变量HOST_IP
|
||||
String hostIpEnv = System.getenv("HOST_IP");
|
||||
if (hostIpEnv != null && !hostIpEnv.isEmpty()) {
|
||||
@@ -26,9 +26,16 @@ public class WorkerIdUtil {
|
||||
if (null == host){
|
||||
try {
|
||||
host = InetAddress.getLocalHost();
|
||||
NetworkInterface networkInterface = NetworkInterface.getByInetAddress(host);
|
||||
if (networkInterface != null) {
|
||||
mac = networkInterface.getHardwareAddress();
|
||||
}
|
||||
} catch (UnknownHostException e) {
|
||||
log.error("[workerId] 获取不到localhost的ip");
|
||||
throw new RuntimeException(e);
|
||||
} catch (SocketException e) {
|
||||
log.error("[workerId] 获取不到ip {} 的 mac地址", ip);
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
ip = host.getHostAddress();
|
||||
@@ -39,35 +46,6 @@ public class WorkerIdUtil {
|
||||
throw new RuntimeException("[workerId] 获取不到ip");
|
||||
}
|
||||
|
||||
byte[] mac = null;
|
||||
|
||||
// 只有在没有使用环境变量且host不为null的情况下才尝试获取MAC地址
|
||||
try {
|
||||
NetworkInterface networkInterface = NetworkInterface.getByInetAddress(host);
|
||||
if (networkInterface != null) {
|
||||
mac = networkInterface.getHardwareAddress();
|
||||
}
|
||||
} catch (SocketException e) {
|
||||
log.error("[workerId] 获取不到ip {} 的 mac地址", ip);
|
||||
}
|
||||
|
||||
// 如果通过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");
|
||||
|
@@ -16,7 +16,7 @@ import java.util.Date;
|
||||
@TableName("bill_record")
|
||||
public class BillRecord{
|
||||
|
||||
@TableId(value = "bill_id", type = IdType.ASSIGN_ID)
|
||||
@TableId(value = "bill_id", type = IdType.INPUT)
|
||||
private Long billId;
|
||||
|
||||
private Long uid;
|
||||
|
Reference in New Issue
Block a user