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;
}
}
}
作者:隔壁老郭
个性签名:独学而无友,则孤陋而寡闻。做一个灵魂有趣的人!
如果觉得这篇文章对你有小小的帮助的话,记得在右下角点个“推荐”哦,博主在此感谢!
Java入门到入坟
万水千山总是情,打赏一分行不行,所以如果你心情还比较高兴,也是可以扫码打赏博主,哈哈哈(っ•̀ω•́)っ✎⁾⁾!