Ribbon內置7種負載均衡算法怯疤,通過IRule接口的choose()方法來實現(xiàn)不同的負載均衡算法础拨,我們通過自己實現(xiàn)choose()方法的方式來達到自定義負載均衡策略的目的
IRule接口
需求:每臺機器訪問5次后隨即輪詢
1:消費者主啟動類
添加注解@RibbonClient(name="MICROSERVICECLOUD-DEPT",configuration=MySelfRule.class),用來指定我們自定義的Ribbon配置類
2:創(chuàng)建配置類與choose()方法實現(xiàn)類
@Configuration
public class MySelfRule
{
@Bean
public IRule myRule()
{
return new RandomRule_ZY();// 我自定義為每臺機器5次
}
}
注: 自定義策略源碼是在RandomRule算法上做了修改
public class RandomRule_ZY extends AbstractLoadBalancerRule
{
// total = 0 // 當total==5以后柒傻,我們指針才能往下走,
// index = 0 // 當前對外提供服務的服務器地址,
// total需要重新置為零胀茵,但是已經達到過一個5次,我們的index = 1
// 分析:我們5次挟阻,但是微服務只有8001 8002 8003 三臺琼娘,OK峭弟?
//
private int total = 0; // 總共被調用的次數,目前要求每臺被調用5次
private int currentIndex = 0; // 當前提供服務的機器號
public Server choose(ILoadBalancer lb, Object key)
{
if (lb == null) {
return null;
}
Server server = null;
while (server == null) {
if (Thread.interrupted()) {
return null;
}
//獲取可用的Server集合
List<Server> upList = lb.getReachableServers();
//獲取全部server集合
List<Server> allList = lb.getAllServers();
int serverCount = allList.size();
if (serverCount == 0) {
/*
* No servers. End regardless of pass, because subsequent passes only get more
* restrictive.
*/
return null;
}
// int index = rand.nextInt(serverCount);// java.util.Random().nextInt(3);
// server = upList.get(index);
//服務調用計數
// private int total = 0; // 總共被調用的次數脱拼,目前要求每臺被調用5次
// private int currentIndex = 0; // 當前提供服務的機器號
if(total < 5)
{
server = upList.get(currentIndex);
total++;
}else {
total = 0;
currentIndex++;
if(currentIndex >= upList.size())
{
currentIndex = 0;
}
}
if (server == null) {
/*
* The only time this should happen is if the server list were somehow trimmed.
* This is a transient condition. Retry after yielding.
*/
Thread.yield();
continue;
}
if (server.isAlive()) {
return (server);
}
// Shouldn't actually happen.. but must be transient or a bug.
server = null;
Thread.yield();
}
return server;
}
@Override
public Server choose(Object key)
{
return choose(getLoadBalancer(), key);
}
@Override
public void initWithNiwsConfig(IClientConfig clientConfig)
{
// TODO Auto-generated method stub
}
}
注意:自定義配置類不能放在@ComponentScan所掃描的當前包下以及子包下瞒瘸,否則我們自定義的這個配置類就會被所有的Ribbon客戶端所共享,也就是說熄浓,我們達不到特殊化定制的目的了情臭。
image.png