Ribbon-Loadbalancer自定义负载均衡策略:本地优先+偏向服务器优先

Ribbon 核心顶层抽象

package com.netflix.loadbalancer;
public interface IRule {
    Server choose(Object var1);

    void setLoadBalancer(ILoadBalancer var1);

    ILoadBalancer getLoadBalancer();
}

继承 IRule 实现 choose 方法

默认实现

我们这里说明现有的集成扩展从写

BestAvailableRule

选择一个最小的并发请求的server


import com.netflix.loadbalancer.BestAvailableRule;
import com.netflix.loadbalancer.Server;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

/**
 * 本地优先策略:尽可能选择本地(相同IP)的服务提供者
 */
public class LocalPreferedRule extends BestAvailableRule {

    /**
     * 本机IP地址{搜索本地网卡优先}
     */
    private List<String> ips = new ArrayList<>();

    /**
     * 偏向的IP地址||除了本地优先之外,尽可能少去选择其他开发者的主机
     * 未找到本地优先时偏向使用测试公共环境{10.130.1.11/13/14/15/18/19}
     */
    private String biasIp = "10.130.1.1";

    public LocalPreferedRule() {
        getIpAddress();
    }

    public void getIpAddress() {
        try {
            Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
            InetAddress ip = null;
            while (allNetInterfaces.hasMoreElements()) {
                NetworkInterface netInterface = allNetInterfaces.nextElement();
                if (netInterface.isLoopback() || netInterface.isVirtual() || !netInterface.isUp()) {
                    continue;
                } else {
                    Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
                    while (addresses.hasMoreElements()) {
                        ip = addresses.nextElement();
                        if (ip != null && ip instanceof Inet4Address) {
                            ips.add(ip.getHostAddress());
                        }
                    }
                }
            }
        } catch (Exception e) {
            System.err.println("IP地址获取失败" + e.toString());
        }
    }

    @Override
    public Server choose(Object key) {
        List<Server> serverList = getLoadBalancer().getAllServers();
        Server chosen = null;
        for (Server server : serverList) {
            if (ips.contains(server.getHost())) {
                chosen = server;
            }
            if (chosen == null && server.getHost().contains(biasIp)) {
                chosen = server;
            }
        }
        if (chosen == null) {
            return super.choose(key);
        } else {
            return chosen;
        }
    }
}

posted on 2024-10-15 11:38  白嫖老郭  阅读(10)  评论(0编辑  收藏  举报

导航