一 hystrix的熔斷原理
1.1? hystrix的熔斷原理
在springcloud的框架里,熔斷機制是通過hystrix實現,hystrix會監控服務之間的調用。當失敗調用達到一定的閾值,默認是5s內失敗20次,就會啟用hystrix的熔斷機制,使用命@HystrixCommand。
1.2 觸發原則
斷路器涉及3個重要參數: 快照時間窗口,請求總數閾值,錯誤百分比閾值
1.快照時間窗口:斷路器確定是否打開需要統計一些請求和錯誤數據,開始統計時間范圍為快照時間窗口,默認為最近的10s。
2.請求總數閾值:在快照時間窗內,必須滿足請求總數閾值才能有資格熔斷。默認為20,也就是說10s內,
調用異常的次數大于20則滿足熔斷資格,否則調用次數不足20次,及時所有的請求都超時或者其他原因失敗,斷路器都不會打開。
3.錯誤百分比閾值:當請求總數在快照時間范圍內超出了閾值。比如發生了30次,如果這30次中,有15次發生超時異常,也就是超過了50%的錯誤百分比
在默認設定50%閾值情況下,這時候斷路器將打開。
總結:3個條件是與的關系。
?二 案例操作
2.1 controller代碼配置
1.截圖
?2.代碼
package com.ljf.mscloud.controller;import com.alibaba.nacos.common.utils.UuidUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.json.JsonMapper;
import com.ljf.mscloud.model.User;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.web.bind.annotation.*;/*** @ClassName: ProviderController* @Description: TODO* @Author: admin* @Date: 2023/08/15?19:58:46?* @Version: V1.0**/
@RestController
public class ProviderController {@GetMapping(value = "/ljf/getinfo/{id}")@HystrixCommand(fallbackMethod = "dealFallBackInfo",commandProperties = {@HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value="3000")})public String getPayment(@PathVariable("id") Integer id){try {Thread.sleep(5000);} catch (InterruptedException e) {e.printStackTrace();}int k=10/0;System.out.println("================服務9009 獲取到的參數id:"+id);return "服務9009 獲取到的參數id:"+id;}@PostMapping("/path")public String postQueryParams(@RequestBody User user) throws JsonProcessingException {String str= new JsonMapper().writeValueAsString(user);System.out.println("post提交....");return str;}public String dealFallBackInfo(@PathVariable("id") Long id){return "我是消費者9009,服務出錯了,進行服務降級"+id;}/*** 服務熔斷 **/@HystrixCommand(fallbackMethod = "paymentCircuitBreaker_fallback",commandProperties = {@HystrixProperty(name = "circuitBreaker.enabled",value = "true"),// 是否開啟斷路器@HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"),// 請求次數@HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "10000"), // 時間窗口期@HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "60"),// 失敗率達到多少后跳閘})@GetMapping(value = "/breakdown/info/{id}")public String getBeakDown(@PathVariable("id") Integer id){if(id<0){throw new RuntimeException("參數為負數.....");}String serialNumber = UuidUtils.generateUuid();return Thread.currentThread().getName()+"\t"+"調用成功,流水號: " + serialNumber;}public String paymentCircuitBreaker_fallback(@PathVariable("id") Integer id){return "id 不能負數,請稍后再試,/(ㄒoㄒ)/~~ id: " +id;}
}
2.2 啟動服務測試
1.啟動nacos,啟動sleuth
?2.啟動provider9009 服務
?3.測試
請求為負數,服務熔斷,走服務降級
?請求為正數,多請求幾次,后恢復正常請求
?