spring cloud 集成 ribbon負載均衡的實例代碼
本文比較簡單集成ribbon,如需要更詳細,請查看我的更多博客內容。
首先創(chuàng)建兩個服務提供者

服務一,集成的nacos注冊中心,這塊隨便寫一個同名接口

端口配置8301

服務二,同名接口內容修改,其他跟上一個服務一大體內容一致

端口配置成8302

創(chuàng)建服務消費者

RibbonConfig.java
package com.example.nacosribbonconsumers.config;
import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.RoundRobinRule;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.ribbon.RibbonClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
@Configuration
// 如果多個服務可以選擇不同的策略
/*@RibbonClients({
@RibbonClient(name = "other",configuration = OtherConfig.class),
@RibbonClient(name = "provider",configuration = ProviderConfig.class)
})*/
@RibbonClient(name = "nacos-ribbon-provider")
public class RibbonConfig {
//定義負載均衡規(guī)則
@Bean
public IRule ribbonRule(){
return new RoundRobinRule();
/**
* RoundRobinRule:
* 輪詢規(guī)則
*
* RandomRule:
* 隨機規(guī)則
*
* WeightedResponseTimeRule:
* 使用響應時間的平均或者百分比為每個服務分配權重的規(guī)則,如果沒法收集響應時間信息,會默認使用輪詢規(guī)則
*
* BestAvailableRule:
* 會先根據斷路器過濾掉處于故障的服務,然后選擇并發(fā)量最小的服務
*
* ZoneAvoidanceRule:
* 根據server所在Zone和其性能,選擇服務器,默認規(guī)則
*
* AvailabilityFilteringRule:
* 先根據斷路器規(guī)則過濾掉有問題的服務,然后對剩余的服務按照輪詢的策略進行訪問
*
* RetryRule:
* 先按照RoundRobinRule規(guī)則進行服務獲取,如果調用服務失敗會在指定時間內進行重試,直到獲取到可用的服務。
*/
}
@Bean
@LoadBalanced
public RestTemplate restTemplate(){
return new RestTemplate();
}
}
RibbonTest.java
package com.example.nacosribbonconsumers.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
@RestController
public class RibbonTest {
@Autowired
private RestTemplate restTemplate;
@GetMapping(value = "/ribbon-consumers/ribbon-test")
public String printProviderLog(){
String result = restTemplate.getForObject("http://nacos-ribbon-provider/ribbon-test", String.class);
return result;
}
}
pom包
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-ribbon</artifactId> </dependency>
配置文件

先啟動兩個服務提供者,然后在啟動服務消費者,瀏覽訪問


不斷刷新 發(fā)現使用的輪詢方式交替執(zhí)行。
到此這篇關于spring cloud 集成 ribbon負載均衡的文章就介紹到這了,更多相關spring cloud ribbon負載均衡內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Java實戰(zhàn)之用Spring開發(fā)條形碼和驗證碼
這篇文章主要介紹了Java實戰(zhàn)之用Spring開發(fā)條形碼和驗證碼,文中有非常詳細的代碼示例,對正在學習java的小伙伴們有非常好的幫助,需要的朋友可以參考下2021-04-04
Spring Security中的Servlet過濾器體系代碼分析
這篇文章主要介紹了Spring Security中的Servlet過濾器體系,本文通過圖文并茂的形式給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-07-07

