refactor(core): 替换IP工具类实现

- 将IpUtil和NetUtil迁移至deprecated包并注释掉原始代码
- 引入新的IPTool工具类替代原有功能
- 更新JobTrigger中的IP获取逻辑
- 修改XxlJobExecutor中的IP和端口处理方式
- 使用StringTool替代原有的字符串判断逻辑
pull/72/head
xuxueli 1 month ago
parent 84aae28ca2
commit 48ee4aa712

@ -13,9 +13,9 @@ import com.xxl.job.core.biz.ExecutorBiz;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.biz.model.TriggerParam;
import com.xxl.job.core.enums.ExecutorBlockStrategyEnum;
import com.xxl.job.core.util.IpUtil;
import com.xxl.tool.core.StringTool;
import com.xxl.tool.exception.ThrowableTool;
import com.xxl.tool.http.IPTool;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -192,7 +192,7 @@ public class JobTrigger {
// 5、collection trigger info
StringBuilder triggerMsgSb = new StringBuilder();
triggerMsgSb.append(I18nUtil.getString("jobconf_trigger_type")).append("").append(triggerType.getTitle());
triggerMsgSb.append("<br>").append(I18nUtil.getString("jobconf_trigger_admin_adress")).append("").append(IpUtil.getIp());
triggerMsgSb.append("<br>").append(I18nUtil.getString("jobconf_trigger_admin_adress")).append("").append(IPTool.getIp());
triggerMsgSb.append("<br>").append(I18nUtil.getString("jobconf_trigger_exe_regtype")).append("")
.append( (group.getAddressType() == 0)?I18nUtil.getString("jobgroup_field_addressType_0"):I18nUtil.getString("jobgroup_field_addressType_1") );
triggerMsgSb.append("<br>").append(I18nUtil.getString("jobconf_trigger_exe_regaddress")).append("").append(group.getRegistryList());

@ -10,8 +10,8 @@ import com.xxl.job.core.server.EmbedServer;
import com.xxl.job.core.thread.JobLogFileCleanThread;
import com.xxl.job.core.thread.JobThread;
import com.xxl.job.core.thread.TriggerCallbackThread;
import com.xxl.job.core.util.IpUtil;
import com.xxl.job.core.util.NetUtil;
import com.xxl.tool.core.StringTool;
import com.xxl.tool.http.IPTool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -147,12 +147,13 @@ public class XxlJobExecutor {
private void initEmbedServer(String address, String ip, int port, String appname, String accessToken) throws Exception {
// fill ip port
port = port>0?port: NetUtil.findAvailablePort(9999);
ip = (ip!=null&&ip.trim().length()>0)?ip: IpUtil.getIp();
port = port>0?port: IPTool.getAvailablePort(9999);
ip = StringTool.isNotBlank(ip) ? ip : IPTool.getIp();
// generate address
if (address==null || address.trim().length()==0) {
String ip_port_address = IpUtil.getIpPort(ip, port); // registry-addressdefault use address to registry , otherwise use ip:port if address is null
if (StringTool.isBlank(address)) {
// registry-addressdefault use address to registry , otherwise use ip:port if address is null
String ip_port_address = IPTool.toAddressString(IPTool.toAddress(ip, port));
address = "http://{ip_port}/".replace("{ip_port}", ip_port_address);
}

@ -1,206 +0,0 @@
package com.xxl.job.core.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.UnknownHostException;
import java.util.Enumeration;
import java.util.regex.Pattern;
/**
* ip tool
*
* @author xuxueli 2016-5-22 11:38:05
*/
public class IpUtil {
private static final Logger logger = LoggerFactory.getLogger(IpUtil.class);
private static final String ANYHOST_VALUE = "0.0.0.0";
private static final String LOCALHOST_VALUE = "127.0.0.1";
private static final Pattern IP_PATTERN = Pattern.compile("\\d{1,3}(\\.\\d{1,3}){3,5}$");
private static volatile InetAddress LOCAL_ADDRESS = null;
// ---------------------- valid ----------------------
private static InetAddress toValidAddress(InetAddress address) {
if (address instanceof Inet6Address) {
Inet6Address v6Address = (Inet6Address) address;
if (isPreferIPV6Address()) {
return normalizeV6Address(v6Address);
}
}
if (isValidV4Address(address)) {
return address;
}
return null;
}
private static boolean isPreferIPV6Address() {
return Boolean.getBoolean("java.net.preferIPv6Addresses");
}
/**
* valid Inet4Address
*
* @param address
* @return
*/
private static boolean isValidV4Address(InetAddress address) {
if (address == null || address.isLoopbackAddress()) {
return false;
}
String name = address.getHostAddress();
boolean result = (name != null
&& IP_PATTERN.matcher(name).matches()
&& !ANYHOST_VALUE.equals(name)
&& !LOCALHOST_VALUE.equals(name));
return result;
}
/**
* normalize the ipv6 Address, convert scope name to scope id.
* e.g.
* convert
* fe80:0:0:0:894:aeec:f37d:23e1%en0
* to
* fe80:0:0:0:894:aeec:f37d:23e1%5
* <p>
* The %5 after ipv6 address is called scope id.
* see java doc of {@link Inet6Address} for more details.
*
* @param address the input address
* @return the normalized address, with scope id converted to int
*/
private static InetAddress normalizeV6Address(Inet6Address address) {
String addr = address.getHostAddress();
int i = addr.lastIndexOf('%');
if (i > 0) {
try {
return InetAddress.getByName(addr.substring(0, i) + '%' + address.getScopeId());
} catch (UnknownHostException e) {
// ignore
logger.debug("Unknown IPV6 address: ", e);
}
}
return address;
}
// ---------------------- find ip ----------------------
private static InetAddress getLocalAddress0() {
InetAddress localAddress = null;
// 1、prefer filter NetworkInterface
try {
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
if (null == interfaces) {
return localAddress;
}
while (interfaces.hasMoreElements()) {
try {
NetworkInterface network = interfaces.nextElement();
if (network.isLoopback() || network.isVirtual() || !network.isUp()) {
continue;
}
Enumeration<InetAddress> addresses = network.getInetAddresses();
while (addresses.hasMoreElements()) {
try {
InetAddress addressItem = toValidAddress(addresses.nextElement());
if (addressItem != null) {
try {
if(addressItem.isReachable(100)){
return addressItem;
}
} catch (IOException e) {
// ignore
}
}
} catch (Throwable e) {
logger.error(e.getMessage(), e);
}
}
} catch (Throwable e) {
logger.error(e.getMessage(), e);
}
}
} catch (Throwable e) {
logger.error(e.getMessage(), e);
}
// 2、getLocalAddress
try {
localAddress = InetAddress.getLocalHost();
InetAddress addressItem = toValidAddress(localAddress);
if (addressItem != null) {
return addressItem;
}
} catch (Throwable e) {
logger.error(e.getMessage(), e);
}
return localAddress;
}
// ---------------------- tool ----------------------
/**
* Find first valid IP from local network card
*
* @return first valid local IP
*/
public static InetAddress getLocalAddress() {
if (LOCAL_ADDRESS != null) {
return LOCAL_ADDRESS;
}
InetAddress localAddress = getLocalAddress0();
LOCAL_ADDRESS = localAddress;
return localAddress;
}
/**
* get ip address
*
* @return String
*/
public static String getIp(){
return getLocalAddress().getHostAddress();
}
/**
* get ip:port
*
* @param port
* @return String
*/
public static String getIpPort(int port){
String ip = getIp();
return getIpPort(ip, port);
}
public static String getIpPort(String ip, int port){
if (ip==null) {
return null;
}
return ip.concat(":").concat(String.valueOf(port));
}
public static Object[] parseIpPort(String address){
String[] array = address.split(":");
String host = array[0];
int port = Integer.parseInt(array[1]);
return new Object[]{host, port};
}
}

@ -1,70 +0,0 @@
package com.xxl.job.core.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.ServerSocket;
/**
* net util
*
* @author xuxueli 2017-11-29 17:00:25
*/
public class NetUtil {
private static Logger logger = LoggerFactory.getLogger(NetUtil.class);
/**
* find available port
*
* @param defaultPort
* @return
*/
public static int findAvailablePort(int defaultPort) {
int portTmp = defaultPort;
while (portTmp < 65535) {
if (!isPortUsed(portTmp)) {
return portTmp;
} else {
portTmp++;
}
}
portTmp = defaultPort - 1;
while (portTmp > 0) {
if (!isPortUsed(portTmp)) {
return portTmp;
} else {
portTmp--;
}
}
throw new RuntimeException("no available port.");
}
/**
* check port used
*
* @param port
* @return
*/
public static boolean isPortUsed(int port) {
boolean used = false;
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(port);
used = false;
} catch (IOException e) {
logger.info(">>>>>>>>>>> xxl-job, port[{}] is in use.", port);
used = true;
} finally {
if (serverSocket != null) {
try {
serverSocket.close();
} catch (IOException e) {
logger.info("");
}
}
}
return used;
}
}

@ -0,0 +1,206 @@
//package com.xxl.job.core.util;
//
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//
//import java.io.IOException;
//import java.net.Inet6Address;
//import java.net.InetAddress;
//import java.net.NetworkInterface;
//import java.net.UnknownHostException;
//import java.util.Enumeration;
//import java.util.regex.Pattern;
//
///**
// * ip tool
// *
// * @author xuxueli 2016-5-22 11:38:05
// */
//public class IpUtil {
// private static final Logger logger = LoggerFactory.getLogger(IpUtil.class);
//
// private static final String ANYHOST_VALUE = "0.0.0.0";
// private static final String LOCALHOST_VALUE = "127.0.0.1";
// private static final Pattern IP_PATTERN = Pattern.compile("\\d{1,3}(\\.\\d{1,3}){3,5}$");
//
//
//
// private static volatile InetAddress LOCAL_ADDRESS = null;
//
// // ---------------------- valid ----------------------
//
// private static InetAddress toValidAddress(InetAddress address) {
// if (address instanceof Inet6Address) {
// Inet6Address v6Address = (Inet6Address) address;
// if (isPreferIPV6Address()) {
// return normalizeV6Address(v6Address);
// }
// }
// if (isValidV4Address(address)) {
// return address;
// }
// return null;
// }
//
// private static boolean isPreferIPV6Address() {
// return Boolean.getBoolean("java.net.preferIPv6Addresses");
// }
//
// /**
// * valid Inet4Address
// *
// * @param address
// * @return
// */
// private static boolean isValidV4Address(InetAddress address) {
// if (address == null || address.isLoopbackAddress()) {
// return false;
// }
// String name = address.getHostAddress();
// boolean result = (name != null
// && IP_PATTERN.matcher(name).matches()
// && !ANYHOST_VALUE.equals(name)
// && !LOCALHOST_VALUE.equals(name));
// return result;
// }
//
//
// /**
// * normalize the ipv6 Address, convert scope name to scope id.
// * e.g.
// * convert
// * fe80:0:0:0:894:aeec:f37d:23e1%en0
// * to
// * fe80:0:0:0:894:aeec:f37d:23e1%5
// * <p>
// * The %5 after ipv6 address is called scope id.
// * see java doc of {@link Inet6Address} for more details.
// *
// * @param address the input address
// * @return the normalized address, with scope id converted to int
// */
// private static InetAddress normalizeV6Address(Inet6Address address) {
// String addr = address.getHostAddress();
// int i = addr.lastIndexOf('%');
// if (i > 0) {
// try {
// return InetAddress.getByName(addr.substring(0, i) + '%' + address.getScopeId());
// } catch (UnknownHostException e) {
// // ignore
// logger.debug("Unknown IPV6 address: ", e);
// }
// }
// return address;
// }
//
// // ---------------------- find ip ----------------------
//
//
// private static InetAddress getLocalAddress0() {
// InetAddress localAddress = null;
// // 1、prefer filter NetworkInterface
// try {
// Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
// if (null == interfaces) {
// return localAddress;
// }
// while (interfaces.hasMoreElements()) {
// try {
// NetworkInterface network = interfaces.nextElement();
// if (network.isLoopback() || network.isVirtual() || !network.isUp()) {
// continue;
// }
// Enumeration<InetAddress> addresses = network.getInetAddresses();
// while (addresses.hasMoreElements()) {
// try {
// InetAddress addressItem = toValidAddress(addresses.nextElement());
// if (addressItem != null) {
// try {
// if(addressItem.isReachable(100)){
// return addressItem;
// }
// } catch (IOException e) {
// // ignore
// }
// }
// } catch (Throwable e) {
// logger.error(e.getMessage(), e);
// }
// }
// } catch (Throwable e) {
// logger.error(e.getMessage(), e);
// }
// }
// } catch (Throwable e) {
// logger.error(e.getMessage(), e);
// }
//
// // 2、getLocalAddress
// try {
// localAddress = InetAddress.getLocalHost();
// InetAddress addressItem = toValidAddress(localAddress);
// if (addressItem != null) {
// return addressItem;
// }
// } catch (Throwable e) {
// logger.error(e.getMessage(), e);
// }
//
// return localAddress;
// }
//
//
// // ---------------------- tool ----------------------
//
// /**
// * Find first valid IP from local network card
// *
// * @return first valid local IP
// */
// public static InetAddress getLocalAddress() {
// if (LOCAL_ADDRESS != null) {
// return LOCAL_ADDRESS;
// }
// InetAddress localAddress = getLocalAddress0();
// LOCAL_ADDRESS = localAddress;
// return localAddress;
// }
//
// /**
// * get ip address
// *
// * @return String
// */
// public static String getIp(){
// return getLocalAddress().getHostAddress();
// }
//
// /**
// * get ip:port
// *
// * @param port
// * @return String
// */
// public static String getIpPort(int port){
// String ip = getIp();
// return getIpPort(ip, port);
// }
//
// public static String getIpPort(String ip, int port){
// if (ip==null) {
// return null;
// }
// return ip.concat(":").concat(String.valueOf(port));
// }
//
// public static Object[] parseIpPort(String address){
// String[] array = address.split(":");
//
// String host = array[0];
// int port = Integer.parseInt(array[1]);
//
// return new Object[]{host, port};
// }
//
//
//}

@ -0,0 +1,70 @@
//package com.xxl.job.core.util;
//
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//
//import java.io.IOException;
//import java.net.ServerSocket;
//
///**
// * net util
// *
// * @author xuxueli 2017-11-29 17:00:25
// */
//public class NetUtil {
// private static Logger logger = LoggerFactory.getLogger(NetUtil.class);
//
// /**
// * find available port
// *
// * @param defaultPort
// * @return
// */
// public static int findAvailablePort(int defaultPort) {
// int portTmp = defaultPort;
// while (portTmp < 65535) {
// if (!isPortUsed(portTmp)) {
// return portTmp;
// } else {
// portTmp++;
// }
// }
// portTmp = defaultPort - 1;
// while (portTmp > 0) {
// if (!isPortUsed(portTmp)) {
// return portTmp;
// } else {
// portTmp--;
// }
// }
// throw new RuntimeException("no available port.");
// }
//
// /**
// * check port used
// *
// * @param port
// * @return
// */
// public static boolean isPortUsed(int port) {
// boolean used = false;
// ServerSocket serverSocket = null;
// try {
// serverSocket = new ServerSocket(port);
// used = false;
// } catch (IOException e) {
// logger.info(">>>>>>>>>>> xxl-job, port[{}] is in use.", port);
// used = true;
// } finally {
// if (serverSocket != null) {
// try {
// serverSocket.close();
// } catch (IOException e) {
// logger.info("");
// }
// }
// }
// return used;
// }
//
//}
Loading…
Cancel
Save