Hystrix
Hystrix-服務熔斷
2021/09/29 09:00:00
2
1653
前言
複雜的分佈式系統結構中的服務會有多種依賴關係,每個依賴關係有時候將會發生不可避免的錯誤(服務請求反應時間過長或服務不可用)。此種情況就會造成某個服務節點延遲過久造成服務鏈結占用過多的系統資源,導致系統崩潰,這都表示這些錯誤需要被隔離與管理且不可影響服務或是系統運作。
什麼是 Hystrix?
Hystrix 框架能夠保證一個服務出問題的情況下,不會導致整個系統服務失敗,避免級聯故障,以提高分佈式系統的彈性。
Hystrix模式分為服務熔斷、服務降級、服務限流等。
服務熔斷介紹
1. 當檢測到服務出現問題,會快速返回失敗訊息給使用者,系統不至於卡在某個點節服務過久。
2. 監控各個服務,判斷服務是否能恢復正常運作。
Hystrix服務熔斷 -- 配置與測試
1. 在pom.xml 導入相關依賴
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix</artifactId>
<version>1.4.7.RELEASE</version>
</dependency>
2. 在springboot 主啟動類加上@EnableCircuitBreaker開始服務熔斷功能。
package com.jason;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
@EnableCircuitBreaker
@SpringBootApplication
public class hystrix_test_8001 {
public static void main(String[] args){
SpringApplication.run(hystrix_test_8001.class,args);
}
}
3. 在Controller 請求方法上加上@HystrixCommand(fallbackmethod="將處理錯誤之方法名稱")
package com.jason.controller;
import com.jason.pojo.Dept;
import com.jason.service.DeptServiceImpl;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
public class DeptController {
@Autowired
private DeptServiceImpl deptService;
@HystrixCommand(fallbackMethod = "hystrixFind")
@GetMapping("dept/find/{id}")
public Dept findDept(@PathVariable("id") Long id){
Dept dept = deptService.findDept(id);
if(dept == null){
throw new RuntimeException("編號" + id + " 部門,找不到唷");
}
return dept;
}
public Dept hystrixFind(@PathVariable("id") Long id){
Dept dept = new Dept();
dept.setDeptno(id);
dept.setDeptname("@Hystrix~ 這個部門id => " + id + ",没有對應的資料,null");
dept.setManager("沒有對應的主管");
return dept;
}
}
4. 啟動springBoot,對該方法送請求查詢對應的部門資料
4-1 請求成功
4-2 請求失敗
5. 沒有使用hystrix 對相同地址發送請求的情況
因此,服務熔斷可以避免因某個服務出現異常或是錯誤導致整個應用或網頁出錯。
參考文獻:
狂神springCloud課程