1. 程式人生 > 其它 >dubbo服務多網絡卡IP問題

dubbo服務多網絡卡IP問題

起因

更換電腦,dubbo服務不能除錯,win7電腦好使,win10不行

分析

經過除錯發現註冊的ip地址,不是VPN分配的地址,多方面查詢資料說ip排序的問題,嘗試一下方法:

  • 網路連線重新命名成一樣的
  • 設定網路活躍點數
  • 2臺電腦java版本安裝一致

以上測試都不能解決,於是除錯程式碼,發現NetUtils獲取網絡卡是直接取的第一塊網絡卡的地址,由於是靜態物件,這樣啟動的時候,根據自己的規則先獲取下,賦個初值就可以了,程式碼如下:

package com.masg.test;

import com.alibaba.dubbo.common.utils.NetUtils;
import com.alibaba.dubbo.container.Main;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.UnknownHostException;
import java.util.Enumeration;
import java.util.regex.Pattern;

public class StartMain {

    public static void setFinalStatic(Field field, Object newValue) throws Exception {
        field.setAccessible(true);
        Field modifiersField = Field.class.getDeclaredField("modifiers");
        modifiersField.setAccessible(true);
        modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
        field.set(null, newValue);
    }


    public static InetAddress getLocalHost() throws UnknownHostException {
        Pattern IP_PATTERN = Pattern.compile("\\d{1,2}(\\.\\d{1,3}){3,5}$");
        try {
            Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
            if (interfaces != null) {
                while (interfaces.hasMoreElements()) {
                    NetworkInterface network = (NetworkInterface) interfaces.nextElement();
                    Enumeration<InetAddress> addresses = network.getInetAddresses();
                    if (addresses != null) {
                        while (addresses.hasMoreElements()) {
                            InetAddress address = (InetAddress) addresses.nextElement();
                            if (address != null && !address.isLoopbackAddress()) {
                                String name = address.getHostAddress();
                                if (name != null && !"0.0.0.0".equals(name) && !"127.0.0.1".equals(name) && IP_PATTERN.matcher(name).matches()) {
                                    return address;
                                }
                            }
                        }
                    }
                }
            }
        } catch (Throwable var8) {
        }
        return null;
    }

    public static void main(String[] args) throws Exception {
        NetUtils net = new NetUtils();
        InetAddress address = getLocalHost();

        Class<NetUtils> netUtilsClass = (Class<NetUtils>) net.getClass();
        Field LOCAL_ADDRESS = netUtilsClass.getDeclaredField("LOCAL_ADDRESS");
        setFinalStatic(LOCAL_ADDRESS, address);

        System.setProperty("dubbo.protocol.dubbo.host", address.getHostAddress()); 
 

        Main.main(args);
    }
}