聊聊SpringCloud中的Ribbon進行服務(wù)調(diào)用的問題
前置內(nèi)容
(1)、微服務(wù)理論入門和手把手帶你進行微服務(wù)環(huán)境搭建及支付、訂單業(yè)務(wù)編寫
(2)、SpringCloud之Eureka服務(wù)注冊與發(fā)現(xiàn)
(3)、SpringCloud之Zookeeper進行服務(wù)注冊與發(fā)現(xiàn)
(4)、SpringCloud之Consul進行服務(wù)注冊與發(fā)現(xiàn)
1、Robbon
1.1、Ribbon概述
(1)、Ribbon是什么?
SpringCloud-Ribbon是基于Netflix Ribbon實現(xiàn)的一套客戶端負載均衡的工具。- 簡單來說,
Ribbon是Netflix發(fā)布的開源項目,主要功能是提供客戶端的軟件負載均衡算法和服務(wù)調(diào)用。Ribbon客戶端組件提供一系列完善的配置如連接超時、重拾等。簡單的說,就是在配置文件中列出Load Balancer(簡稱LB)后面的所有機器,Ribbon會自動的幫助你基于某種規(guī)則(如簡單輪詢,隨即連接等)去連接這些機器。我們很容易使用Ribbon實現(xiàn)自定義的負載均衡算法。 - 一句話就是 負載均衡+RestTemplate調(diào)用。
(2)、Ribbon的官網(wǎng)
且目前也進入了維護模式
(3)、負載均衡(LB)
- 負載均衡就是將用戶的請求平攤的分配到多個服務(wù)上,從而達到系統(tǒng)的
HA(高可用)。常見的負載均衡由軟件nginx、LVS、F5。
1.集中式LB:就是在服務(wù)的消費方和提供方之間使用獨立的LB設(shè)施(可以是硬件,如F5,也可以是軟件,如nginx),由該設(shè)施負責把訪問請求通過某種策略轉(zhuǎn)發(fā)至服務(wù)的提供方。
2.進程內(nèi)LB:將LB邏輯集成到消費方,消費方從服務(wù)注冊中心獲知有哪些地址可用,然后自己再從這些地址中選擇出一個合適的服務(wù)器。Ribbon就屬于進程內(nèi)LB,它只是一個類庫,集成于消費方進程,消費方通過它來獲取服務(wù)提供方的地址。
(4)、Ribbon本地負載均衡客戶端和Nginx服務(wù)端負載均衡的區(qū)別
Nginx是服務(wù)器負載均衡,客戶端所有請求都會交給nginx實現(xiàn)轉(zhuǎn)發(fā)請求。即負載均衡是由服務(wù)端實現(xiàn)的。Ribbon本地負載均衡,在調(diào)用微服務(wù)接口的時候,會在注冊中心獲取注冊信息列表之后緩存到JVM本地,從而在本地實現(xiàn)RPC遠程服務(wù)調(diào)用技術(shù)。
1.2、Ribbon負載均衡演示
(1)、架構(gòu)說明
Ribbon其實就是一個軟負載均衡的客戶端組件,他可以和其他所需請求的客戶端結(jié)合使用,和eureka結(jié)合只是其中的一個實例。

Ribbon在工作時分為兩步
- 第一步先選擇
EurekaServer,他優(yōu)先選擇在同一個區(qū)域內(nèi)負載較少的server。 - 第二步再根據(jù)用戶指定的策略,在從
server取到的服務(wù)注冊列表中選擇一個地址。其中Ribbon提供了多種策略:比如輪詢、隨機和根據(jù)響應(yīng)時間加權(quán)。
(2)、POM文件

所以在引入Eureka的整合包中就包含了整合Ribbon的jar包。
所以我們前面實現(xiàn)的8001和8002交替訪問的方式就是所謂的負載均衡。
(3)、RestTemplate的說明
getForObject:返回對象為響應(yīng)體中數(shù)據(jù)轉(zhuǎn)化成的對象,基本上可以理解為Json。getForEntity:返回對象為ResponseEntity對象,包含了響應(yīng)中的一些重要信息,比如響應(yīng)頭、響應(yīng)狀態(tài)碼、響應(yīng)體等。postForObjectpostForEntity
1.3、Ribbon核心組件IRule

1. 主要的負載規(guī)則
RoundRobinRule:輪詢RandomRule:隨機RetryRule:先按照RoundRobinRule的策略獲取服務(wù),如果獲取服務(wù)失敗則在指定時間內(nèi)會進行重試WeightedResponseTimeRule:對RoundRobinRule的擴展,響應(yīng)速度越快的實例選擇權(quán)重越大,越容易被選擇BestAvailableRule:會先過濾掉由于多次訪問故障而處于斷路器跳閘狀態(tài)的服務(wù),然后選擇一個并發(fā)量最小的服務(wù)AvailabilityFilteringRule:先過濾掉故障實例,再選擇并發(fā)較小的實例ZoneAvoidanceRule:默認規(guī)則,復合判斷server所在區(qū)域的性能和server的可用性選擇服務(wù)器
2. 如何替換負載規(guī)則
- 對
cloud-consumer-order80包下的配置進行修改。 - 我們自己自定義的配置類不能放在
@ComponentScan所掃描的當前包以及子包下,否則我們自定義的這個配置類就會被所有的Ribbon客戶端所共享,達不到特殊化定制的目的了。 - 在
com.xiao的包下新建一個myrule的子包。

- 在
myrule的包下新建一個MySelfRule配置類
???????
import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.RandomRule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MySelfRule {
@Bean
public IRule getRandomRule(){
return new RandomRule(); // 新建隨機訪問負載規(guī)則
}
}- 對主啟動類進行修改,修改為如下:
import com.xiao.myrule.MySelfRule;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.ribbon.RibbonClient;
@SpringBootApplication
@EnableEurekaClient
@RibbonClient(name = "CLOUD-PAYMENT-SERVICE",configuration = MySelfRule.class)
public class OrderMain80 {
public static void main(String[] args) {
SpringApplication.run(OrderMain80.class,args);
}
}6.測試結(jié)果 結(jié)果就是以我們最新配置的隨機方式進行訪問的。
1.4、Ribbon負載均衡算法
1.4.1、輪詢算法原理 負載均衡算法:
rest接口第幾次請求數(shù) % 服務(wù)器集群總數(shù)量 = 實際調(diào)用服務(wù)器位置下標,每次服務(wù)重新啟動后rest接口計數(shù)從1開始。

1.4.2、RoundRobinRule 源碼
import com.netflix.client.config.IClientConfig;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class RoundRobinRule extends AbstractLoadBalancerRule {
private AtomicInteger nextServerCyclicCounter;
private static final boolean AVAILABLE_ONLY_SERVERS = true;
private static final boolean ALL_SERVERS = false;
private static Logger log = LoggerFactory.getLogger(RoundRobinRule.class);
public RoundRobinRule() {
this.nextServerCyclicCounter = new AtomicInteger(0);
}
public RoundRobinRule(ILoadBalancer lb) {
this();
this.setLoadBalancer(lb);
}
public Server choose(ILoadBalancer lb, Object key) {
if (lb == null) {
log.warn("no load balancer");
return null;
} else {
Server server = null;
int count = 0;
while(true) {
if (server == null && count++ < 10) {
// 獲取狀態(tài)為up的服務(wù)提供者
List<Server> reachableServers = lb.getReachableServers();
// 獲取所有的服務(wù)提供者
List<Server> allServers = lb.getAllServers();
int upCount = reachableServers.size();
int serverCount = allServers.size();
if (upCount != 0 && serverCount != 0) {
// 對取模獲得的下標進行獲取相關(guān)的服務(wù)提供者
int nextServerIndex = this.incrementAndGetModulo(serverCount);
server = (Server)allServers.get(nextServerIndex);
if (server == null) {
Thread.yield();
} else {
if (server.isAlive() && server.isReadyToServe()) {
return server;
}
server = null;
continue;
}
log.warn("No up servers available from load balancer: " + lb);
return null;
}
if (count >= 10) {
log.warn("No available alive servers after 10 tries from load balancer: " + lb);
}
return server;
}
}
}
private int incrementAndGetModulo(int modulo) {
int current;
int next;
do {
// 先加一再取模
current = this.nextServerCyclicCounter.get();
next = (current + 1) % modulo;
// CAS判斷,如果判斷成功就返回true,否則就一直自旋
} while(!this.nextServerCyclicCounter.compareAndSet(current, next));
return next;
}
}1.4.3、手寫輪詢算法
1. 修改支付模塊的Controller
添加以下內(nèi)容
@GetMapping(value = "/payment/lb")
public String getPaymentLB(){
return ServerPort;
}2. ApplicationContextConfig去掉@LoadBalanced注解
3. LoadBalancer接口
import org.springframework.cloud.client.ServiceInstance;
import java.util.List;
public interface LoadBalancer {
//收集服務(wù)器總共有多少臺能夠提供服務(wù)的機器,并放到list里面
ServiceInstance instances(List<ServiceInstance> serviceInstances);
}4. 編寫MyLB類
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
@Component
public class MyLB implements LoadBalancer {
private AtomicInteger atomicInteger = new AtomicInteger(0);
//坐標
private final int getAndIncrement(){
int current;
int next;
do {
current = this.atomicInteger.get();
next = current >= 2147483647 ? 0 : current + 1;
}while (!this.atomicInteger.compareAndSet(current,next)); //第一個參數(shù)是期望值,第二個參數(shù)是修改值是
System.out.println("*******第幾次訪問,次數(shù)next: "+next);
return next;
}
@Override
public ServiceInstance instances(List<ServiceInstance> serviceInstances) { //得到機器的列表
int index = getAndIncrement() % serviceInstances.size(); //得到服務(wù)器的下標位置
return serviceInstances.get(index);
}
}5. 修改OrderController類
import com.xiao.cloud.entities.CommonResult;
import com.xiao.cloud.entities.Payment;
import com.xiao.cloud.lb.LoadBalancer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import javax.annotation.Resource;
import java.net.URI;
import java.util.List;
@RestController
@Slf4j
public class OrderController {
// public static final String PAYMENT_URL = "http://localhost:8001";
public static final String PAYMENT_URL = "http://CLOUD-PAYMENT-SERVICE";
@Resource
private RestTemplate restTemplate;
@Resource
private LoadBalancer loadBalancer;
@Resource
private DiscoveryClient discoveryClient;
@GetMapping("/consumer/payment/create")
public CommonResult<Payment> create( Payment payment){
return restTemplate.postForObject(PAYMENT_URL+"/payment/create",payment,CommonResult.class); //寫操作
}
@GetMapping("/consumer/payment/get/{id}")
public CommonResult<Payment> getPayment(@PathVariable("id") Long id){
return restTemplate.getForObject(PAYMENT_URL+"/payment/get/"+id,CommonResult.class);
}
@GetMapping("/consumer/payment/getForEntity/{id}")
public CommonResult<Payment> getPayment2(@PathVariable("id") Long id){
ResponseEntity<CommonResult> entity = restTemplate.getForEntity(PAYMENT_URL+"/payment/get/"+id,CommonResult.class);
if (entity.getStatusCode().is2xxSuccessful()){
// log.info(entity.getStatusCode()+"\t"+entity.getHeaders());
return entity.getBody();
}else {
return new CommonResult<>(444,"操作失敗");
}
}
@GetMapping(value = "/consumer/payment/lb")
public String getPaymentLB(){
List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
if (instances == null || instances.size() <= 0){
return null;
}
ServiceInstance serviceInstance = loadBalancer.instances(instances);
URI uri = serviceInstance.getUri();
return restTemplate.getForObject(uri+"/payment/lb",String.class);
}
}6. 測試結(jié)果
- 最后是在
8001和8002兩個之間進行輪詢訪問。 - 控制臺輸出如下

7. 包結(jié)構(gòu)示意圖

到此這篇關(guān)于SpringCloud中的Ribbon進行服務(wù)調(diào)用的文章就介紹到這了,更多相關(guān)SpringCloud Ribbon服務(wù)調(diào)用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java中使用MongoDB數(shù)據(jù)庫實例Demo
MongoDB是由C++語言編寫的,基于分布式文件存儲的數(shù)據(jù)庫,是一個介于關(guān)系數(shù)據(jù)庫和非關(guān)系數(shù)據(jù)庫之間的產(chǎn)品,是最接近于關(guān)系型數(shù)據(jù)庫的NoSQL數(shù)據(jù)庫,下面這篇文章主要給大家介紹了關(guān)于Java中使用MongoDB數(shù)據(jù)庫的相關(guān)資料,需要的朋友可以參考下2023-12-12
Spring Security 實現(xiàn)“記住我”功能及原理解析
這篇文章主要介紹了Spring Security 實現(xiàn)“記住我”功能及原理解析,需要的朋友可以參考下2020-05-05
Java?Chassis3熔斷機制的改進路程技術(shù)解密
這篇文章主要介紹了Java?Chassis?3技術(shù)解密之熔斷機制的改進路程實例分析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2024-01-01
jackson使用@JsonSerialize格式化BigDecimal解決.00不顯示問題
這篇文章主要介紹了jackson使用@JsonSerialize格式化BigDecimal解決.00不顯示問題,本文直接給出實現(xiàn)代碼,需要的朋友可以參考下2015-02-02
springboot 傳參校驗@Valid及對其的異常捕獲方式
這篇文章主要介紹了springboot 傳參校驗@Valid及對其的異常捕獲方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-10-10

