package com.tmerclub.cloud.common.dubbo;

import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.cluster.loadbalance.RandomLoadBalance;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.List;

/**
 * 以下轮询算法仅在测试环境使用
 * 是本地有服务优先负债到本地服务的算法
 * @author LGH
 */
public class DevProximityLoadBalance extends RandomLoadBalance {

    private final String LOCALHOST;

    private static final String LOCAL_IP = "192.168.0.";

    public DevProximityLoadBalance() throws UnknownHostException {
        InetAddress localHost = InetAddress.getLocalHost();
        LOCALHOST = localHost.getHostAddress();
    }

    @Override
    protected <T> Invoker<T> doSelect(List<Invoker<T>> invokers, URL url, Invocation invocation) {
        if (invokers.size()==1) {
            return invokers.get(0);
        }
        if (!LOCALHOST.contains(LOCAL_IP)) {
            return super.doSelect(invokers, url, invocation);
        }
        for (Invoker<T> invoker : invokers) {
            if (LOCALHOST.contains(invoker.getUrl().getHost())) {
                return invoker;
            }
        }
        return super.doSelect(invokers, url, invocation);
    }
}
