dubbo指定provider的IP

背景:因为自己mac电脑在连接公司启dubbo项目的时候,dubbo直接用的的ip地址,但是这个IP地址ping不通,所以根本没办法用。网上找了一遍,只说了需要配置host,但是我配置了127.0.0.1没用,翻了源码,发现源码里面给我排除了。。。最后我用了外网地址。然后不停MMP。。。

解决办法:

<dubbo:protocol host="192.168.3.221"/>

或者在vm里面加参数:

-Ddubbo.protocol.host=192.168.3.221

分析:

//dubbo-2.5.3-ai-sources.jar!/com/alibaba/dubbo/config/ServiceConfig.java#doExportUrlsFor1Protocol
if (NetUtils.isInvalidLocalHost(host)) {//这里判断是否合法
    host = NetUtils.getLocalHost();
}
//然后是否合法里面直接排除了所有的127开头的IP
private static final Pattern LOCAL_IP_PATTERN = Pattern.compile("127(\\.\\d{1,3}){3}$”);

public static boolean isInvalidLocalHost(String host) {
    return host == null 
             || host.length() == 0
                || host.equalsIgnoreCase("localhost")
                || host.equals("0.0.0.0")
                || (LOCAL_IP_PATTERN.matcher(host).matches());
}

如果不合法,需要遍历电脑所有的网卡,获取有用的IP

//dubbo-2.5.3-ai-sources.jar!/com/alibaba/dubbo/common/utils/NetUtils.java#getLocalAddress0
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
if (interfaces != null) {
    while (interfaces.hasMoreElements()) {
        try {
            NetworkInterface network = interfaces.nextElement();
            Enumeration<InetAddress> addresses = network.getInetAddresses();
            if (addresses != null) {
                while (addresses.hasMoreElements()) {
                    try {
                        InetAddress address = addresses.nextElement();
                        if (isValidAddress(address)) {
                            return address;
                        }
                    } catch (Throwable e) {
                        logger.warn("Failed to retriving ip address, " + e.getMessage(), e);
                    }
                }
            }
        } catch (Throwable e) {
            logger.warn("Failed to retriving ip address, " + e.getMessage(), e);
        }
    }
}

你可能感兴趣的:(java,java,dubbo)