Gateway group support server that have multi ip address

This commit is contained in:
hongqiaowei
2021-09-28 13:39:57 +08:00
parent a5a03c7aa2
commit 11947dec91
2 changed files with 38 additions and 25 deletions

View File

@@ -27,6 +27,9 @@ import java.net.SocketException;
import java.net.UnknownHostException;
import java.security.SecureRandom;
import java.util.Enumeration;
import java.util.LinkedHashSet;
import java.util.Optional;
import java.util.Set;
/**
* @author hongqiaowei
@@ -42,43 +45,51 @@ public class NetworkUtils {
private static String serverIp;
private static Set<String> serverIps = new LinkedHashSet<>();
private static final String SERVER_IP = "SERVER_IP";
/**
* @return user settings, or the first one in ip address list.
*/
public static String getServerIp() {
try {
if (serverIp == null) {
serverIp = System.getProperty(SERVER_IP);
log.info("JVM env SERVER_IP is " + serverIp);
if (StringUtils.isBlank(serverIp)) {
serverIp = System.getenv(SERVER_IP);
log.info("System env SERVER_IP is " + serverIp);
serverIp = getServerIps().iterator().next();
}
if (StringUtils.isBlank(serverIp)) {
boolean found = false;
Enumeration<NetworkInterface> nis = null;
nis = NetworkInterface.getNetworkInterfaces();
return serverIp;
}
public static Set<String> getServerIps() {
try {
if (serverIps.isEmpty()) {
String ip = System.getProperty(SERVER_IP);
if (StringUtils.isBlank(ip)) {
ip = System.getenv(SERVER_IP);
}
if (StringUtils.isBlank(ip)) {
Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces();
while (nis.hasMoreElements()) {
NetworkInterface ni = (NetworkInterface) nis.nextElement();
Enumeration<InetAddress> ias = ni.getInetAddresses();
while (ias.hasMoreElements()) {
InetAddress ia = ias.nextElement();
if (ia.isSiteLocalAddress()) {
serverIp = ia.getHostAddress();
found = true;
break;
ip = ia.getHostAddress();
serverIps.add(ip);
}
}
if (found) {
break;
}
}
if (!found) {
if (serverIps.isEmpty()) {
InetAddress ia = InetAddress.getLocalHost();
serverIp = ia.getHostAddress();
ip = ia.getHostAddress();
serverIps.add(ip);
}
} else {
serverIps.add(ip);
}
log.info("server ip: {}", serverIps);
}
return serverIp;
return serverIps;
} catch (SocketException | UnknownHostException e) {
throw new RuntimeException(e);
}

View File

@@ -184,12 +184,14 @@ public class GatewayGroupService {
private void updateCurrentGatewayGroupSet(Set<String> currentGatewayGroupSet, Map<String,
GatewayGroup> gatewayGroupMap) {
String ip = NetworkUtils.getServerIp();
Set<String> ips = NetworkUtils.getServerIps();
String applicationName = environment.getProperty("spring.application.name");
currentGatewayGroupSet.clear();
gatewayGroupMap.forEach(
(k, gg) -> {
if (gg.gateways.contains(ip) || gg.gateways.contains(applicationName)) {
Set<String> set = new HashSet<>(ips);
set.retainAll(gg.gateways);
if (!set.isEmpty() || gg.gateways.contains(applicationName)) {
currentGatewayGroupSet.add(gg.group);
}
}