当内置的负载均衡策略不满足业务需求的时候,我们就需要自定义 Ribbon 的负载策略。
一、 继承 AbstractLoadBalancerRule 类
package com.comsys.configuration;
import java.util.List;
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;
public class RoncooCustomRule extends AbstractLoadBalancerRule {
private Server choose(ILoadBalancer lb, Object key) {
if (lb == null) {
return null;
}
Server server = null;
while (server == null) {
if (Thread.interrupted()) {
return null;
}
List<Server> upList = lb.getReachableServers(); // 可用的服务实例
// 只获取端口为:7779 的服务实例
for (Server s : upList) {
if (s.getPort() == 7777) {
server = s;
}
}
if (server == null) {
Thread.yield();
continue;
}
System.out.println("实例 IP:" + server.getHost() + " 端口:" +
server.getPort());
if (server.isAlive()) {
return (server);
}
server = null;
Thread.yield();
}
return server;
}
@Override
public Server choose(Object key) {
return choose(getLoadBalancer(), key);
}
@Override
public void initWithNiwsConfig(IClientConfig arg0) {
}
}
二、 配置策略
# 通过配置文件
spring-cloud-provider.ribbon.NFLoadBalancerRuleClassName=com.roncoo.education.configuration.RoncooCustomRule