fix github issues/3652

This commit is contained in:
hubin 2021-08-14 13:05:33 +08:00
parent b988866c3d
commit f63065270c

View File

@ -15,15 +15,12 @@
*/ */
package com.baomidou.mybatisplus.core.toolkit; package com.baomidou.mybatisplus.core.toolkit;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import org.apache.ibatis.logging.Log; import org.apache.ibatis.logging.Log;
import org.apache.ibatis.logging.LogFactory; import org.apache.ibatis.logging.LogFactory;
import java.lang.management.ManagementFactory; import java.lang.management.ManagementFactory;
import java.net.InetAddress; import java.net.InetAddress;
import java.net.NetworkInterface; import java.net.NetworkInterface;
import java.net.UnknownHostException;
import java.util.Optional;
import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.ThreadLocalRandom;
/** /**
@ -74,7 +71,9 @@ public class Sequence {
* 上次生产 ID 时间戳 * 上次生产 ID 时间戳
*/ */
private long lastTimestamp = -1L; private long lastTimestamp = -1L;
/**
* IP 地址
*/
private InetAddress inetAddress; private InetAddress inetAddress;
/** /**
@ -82,7 +81,6 @@ public class Sequence {
*/ */
@Deprecated @Deprecated
public Sequence() { public Sequence() {
this.inetAddress = getLocalHost();
this.datacenterId = getDatacenterId(maxDatacenterId); this.datacenterId = getDatacenterId(maxDatacenterId);
this.workerId = getMaxWorkerId(datacenterId, maxWorkerId); this.workerId = getMaxWorkerId(datacenterId, maxWorkerId);
} }
@ -93,22 +91,6 @@ public class Sequence {
this.workerId = getMaxWorkerId(datacenterId, maxWorkerId); this.workerId = getMaxWorkerId(datacenterId, maxWorkerId);
} }
private InetAddress getLocalHost() {
try {
return InetAddress.getLocalHost();
} catch (UnknownHostException e) {
throw new MybatisPlusException(e);
}
}
/**
* @return InetAddress
* @since 3.4.3
*/
protected InetAddress getInetAddress() {
return Optional.ofNullable(this.inetAddress).orElseGet(this::getLocalHost);
}
/** /**
* 有参构造器 * 有参构造器
* *
@ -149,8 +131,11 @@ public class Sequence {
protected long getDatacenterId(long maxDatacenterId) { protected long getDatacenterId(long maxDatacenterId) {
long id = 0L; long id = 0L;
try { try {
NetworkInterface network = NetworkInterface.getByInetAddress(this.getInetAddress()); if (null == this.inetAddress) {
if (network == null) { this.inetAddress = InetAddress.getLocalHost();
}
NetworkInterface network = NetworkInterface.getByInetAddress(this.inetAddress);
if (null == network) {
id = 1L; id = 1L;
} else { } else {
byte[] mac = network.getHardwareAddress(); byte[] mac = network.getHardwareAddress();