負載均衡-Ribbon 的負載均衡策略
一、 內置負載均衡策略的介紹
1、 BestAvailableRule:選擇一個最小的並發請求的 server,逐個考察 Server,如果 Server 被 tripped 了,則忽略。
2、 AvailabilityFilteringRule:過濾掉那些因為一直連接失敗的被標記為 circuit tripped 的後端 server,並過濾掉那些高並發的的後端 server。
3、 ZoneAvoidanceRule:複合判斷 server 所在區域的性能和 server 的可用性選擇 server。(使用 ZoneAvoidancePredicate 和AvailabilityPredicate 來判斷是否選擇某個 server,前一個判斷判定一個 zone 的運行性能是否可用,剔除不可用的 zone 的所有 server,AvailabilityPredicate 用於過濾掉連接數過多的 Server。)
4、 RandomRule:隨機策略,在 index 上隨機,選擇 index 對應位置的 server。
5、 RetryRule :對選定的負載均衡策略機上重試機制,在一個配置時間段內當選擇 server 不成功,則 一直嘗試使用 subRule 的方式選擇一個可用的 server。
6、 RoundRobinRule:輪詢策略,輪詢 index,選擇 index 對應位置的 server(默認策略)。
7、 WeightedResponseTimeRule:權重策略(基於輪詢策略,根據響應時間分配一個 weight(權重),響 應時間越長,weight 越小,被選中的可能性越低) 。
二、 負載均衡的自定義
1、 通過代碼實現
2、 通過配置文件實現
三、 通過代碼實現
隨機演算法
package com.comsys.education.configuration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.RandomRule;
@Configuration
public class RandomRuleConfig {
@Bean
public IRule randomRule() {
return new RandomRule();
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
配置類:
package com.comsys.education.configuration;
import org.springframework.cloud.netflix.ribbon.RibbonClient;
import org.springframework.context.annotation.Configuration;
@Configuration
@RibbonClient(name = "spring-cloud-provider", configuration = RandomRuleConfig.class)
public class ProviderConfiguration {
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
說明:只需要簡單的 2 個配置,就可以指定輪詢的演算法。
注意:在 RandomRuleConfig 的類裡面,加上@Configuration 註解會導致所有的策略都被覆蓋。
原因:如果 RandomRuleConfig 被 SpringContext 掃描,否則會被@RibbonClients 共用,會覆蓋。
四、 同時使用 2 種以上的不同策略演算法
方法 1:移除@Configuration 註解
package com.comsys.education.configuration;
import org.springframework.context.annotation.Bean;
import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.RoundRobinRule;
// @Configuration
public class RoundRobinRuleConfig {
@Bean
public IRule roundRobinRule() {
return new RoundRobinRule();
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
配置類:
package com.comsys.education.configuration;
import org.springframework.cloud.netflix.ribbon.RibbonClient;
import org.springframework.context.annotation.Configuration;
@Configuration
@RibbonClient(name = "spring-cloud-provider2", configuration = RoundRobinRuleConfig.class)
public class Provider2Configuration {
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
說明:新增 RoundRobinRuleConfig 類,移除@Configuration 註解,同時也要把 RandomRuleConfig 的
@Configuration 註解移除
方法 2:指定@ComponentScan 的掃描路徑(默認是掃描主類下面所有的文件夾) 。
方法 3:把它移到主類的外面,讓主類掃描不到。
說明:只要不讓 SpringContext 掃描到即可。
五、 通過配置配置文件實現不同的演算法 配置文件添加:
#設置策略
spring-cloud-provider.ribbon.NFLoadBalancerRuleClassName=com.netflix.loadbalancer.RandomRule
spring-cloud-provider2.ribbon.NFLoadBalancerRuleClassName=com.netflix.loadbalancer.RandomRule
說明:格式為:應用名.ribbon.NFLoadBalancerRuleClassName=xxx
※Windows下如何查看某個埠被誰佔用
※jsp頁面內嵌另一個jsp公共頁面
TAG:程序員小新人學習 |