1. 程式人生 > >Spring Boot + Spring Cloud 構建微服務系統(二):服務消費和負載(Ribbon)

Spring Boot + Spring Cloud 構建微服務系統(二):服務消費和負載(Ribbon)

使用RestTemplate呼叫服務

在上一篇教程中,我們是這樣呼叫服務的,先通過 LoadBalancerClient 選取出對應的服務,然後使用 RestTemplate 進行遠端呼叫。

LoadBalancerClient 就是負載均衡器,預設使用的是 Ribbon 的實現 RibbonLoadBalancerClient,採用的負載均衡策略是輪詢。

package com.louis.spring.cloud.consul.consumer.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance; import org.springframework.cloud.client.loadbalancer.LoadBalancerClient; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; @RestController
public class RibbonHelloController { @Autowired private LoadBalancerClient loadBalancer; @RequestMapping("/call") public String call() { // 查詢服務 ServiceInstance serviceInstance = loadBalancer.choose("service-producer"); // 呼叫服務 String callServiceResult = new
RestTemplate().getForObject(serviceInstance.getUri().toString() + "/hello", String.class); return callServiceResult; } }

使用Ribbon實現負載均衡

Ribbon介紹

Ribbon是Netflix釋出的負載均衡器,它有助於控制HTTP和TCP的客戶端的行為。為Ribbon配置服務提供者地址後,Ribbon就可基於某種負載均衡演算法,自動地幫助服務消費者去請求。Ribbon預設為我們提供了很多負載均衡演算法,例如輪詢、隨機等。當然,我們也可為Ribbon實現自定義的負載均衡演算法。

ribbon內建負載均衡策略:

策略名 策略宣告 策略描述 實現說明
BestAvailableRule public class BestAvailableRule extends ClientConfigEnabledRoundRobinRule 選擇一個最小的併發請求的server 逐個考察Server,如果Server被tripped了,則忽略,在選擇其中ActiveRequestsCount最小的server
AvailabilityFilteringRule public class AvailabilityFilteringRule extends PredicateBasedRule 過濾掉那些因為一直連線失敗的被標記為circuit tripped的後端server,並過濾掉那些高併發的的後端server(active connections 超過配置的閾值) 使用一個AvailabilityPredicate來包含過濾server的邏輯,其實就就是檢查status裡記錄的各個server的執行狀態
WeightedResponseTimeRule public class WeightedResponseTimeRule extends RoundRobinRule 根據響應時間分配一個weight,響應時間越長,weight越小,被選中的可能性越低。 一個後臺執行緒定期的從status裡面讀取評價響應時間,為每個server計算一個weight。Weight的計算也比較簡單responsetime 減去每個server自己平均的responsetime是server的權重。當剛開始執行,沒有形成status時,使用roubine策略選擇server。
RetryRule public class RetryRule extends AbstractLoadBalancerRule 對選定的負載均衡策略機上重試機制。 在一個配置時間段內當選擇server不成功,則一直嘗試使用subRule的方式選擇一個可用的server
RoundRobinRule public class RoundRobinRule extends AbstractLoadBalancerRule roundRobin方式輪詢選擇server 輪詢index,選擇index對應位置的server
RandomRule public class RandomRule extends AbstractLoadBalancerRule 隨機選擇一個server 在index上隨機,選擇index對應位置的server
ZoneAvoidanceRule public class ZoneAvoidanceRule extends PredicateBasedRule 複合判斷server所在區域的效能和server的可用性選擇server 使用ZoneAvoidancePredicate和AvailabilityPredicate來判斷是否選擇某個server,前一個判斷判定一個zone的執行效能是否可用,剔除不可用的zone(的所有server),AvailabilityPredicate用於過濾掉連線數過多的Server。

修改啟動器

修改 spring-cloud-consul-consumer 工程下的啟動器類,注入 RestTemplate,並新增 @LoadBalanced 註解(用於攔截請求),以使用 ribbon 來進行負載均衡。

package com.louis.spring.cloud.consul.consumer;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
public class ConsuleConsumerApplication {

    public static void main(String[] args) {
        SpringApplication.run(ConsuleConsumerApplication.class, args);
    }

    @Bean
    @LoadBalanced
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
}

 新增服務

新建 RibbonHelloController 類,注入 RestTemplate。

package com.louis.spring.cloud.consul.consumer.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
public class RibbonHelloController {

    @Autowired
    private RestTemplate restTemplate;
    
    @RequestMapping("/ribbon/call")
    public String call() {
        // 呼叫服務, service-producer為註冊的服務名稱,LoadBalancerInterceptor會攔截呼叫並根據服務名找到對應的服務
        String callServiceResult = restTemplate.getForObject("http://service-producer/hello", String.class);
        return callServiceResult;
    }
}

 測試效果

啟動消費者服務,訪問 http://localhost:8521/ribbon/call,依次返回結果如下:

helle consul
helle consul two
...

說明 ribbon 的負載均衡已經成功啟動了。

修改策略

修改負載均衡策略很簡單,只需要在配置檔案指定對應的負載均衡器即可。如這裡把策略修改為隨機策略。

application.yml

#ribbon 負載均衡策略配置, service-producer為註冊的服務名
service-producer:
  ribbon:
    NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule

完成啟動之後,發現 hello consul 和  hello consul two 結果不再交替出現,而是隨機出現,說明策略修改成功了。

 

原始碼下載

碼雲:https://gitee.com/liuge1988/spring-cloud-demo.git


作者:朝雨憶輕塵
出處:https://www.cnblogs.com/xifengxiaoma/ 
版權所有,歡迎轉載,轉載請註明原文作者及出處。