1. 程式人生 > >Srping cloud Ribbon 自定義負載均衡

Srping cloud Ribbon 自定義負載均衡

cer return .class clas pre 均衡 nbsp imm transient

IRule 默認提供有7種方式,使用輪詢方式

如何自定義

1:主啟動類加@RibbonClient

@RibbonClient(name="微服務名", configuration=MySelfRule.class)

技術分享圖片

也就是說MySelfRule.java不能和@SpringBootApplication註釋的類在同一包下.

MySelfRule.java

package com.atguigu.myrule;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.RoundRobinRule;

@Configuration
public class MySelfRule { @Bean public IRule myRule() { //return new RandomRule();// Ribbon默認是輪詢,我自定義為隨機 //return new RoundRobinRule();// Ribbon默認是輪詢,我自定義為隨機 return new RandomRule_ZY();// 我自定義為每臺機器5次 } }

package com.atguigu.myrule;

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 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; } List<Server> upList = lb.getReachableServers(); 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 } }

Srping cloud Ribbon 自定義負載均衡