SpringClound——Hystrix斷路器

SpringCloud學習資料彙總超級棒的
如上是我在看文章時忽然看到的一個很好的學習SpringCloud的網站

SpringClound——微服務概述——史上最爛
SpringClound——SpringClound入門概述——史上最爛
SpringCloud——Eureka——史上最基本
SpringClound——Ribbon負載均衡——史上最爛系列
SpringClound——Feign
SpringClound——Hystrix斷路器

1:Hystrix斷路器介紹

  • Hystrix是一個用於處理分佈式系統的延遲和容錯的開源庫,在分佈式系統裏,許多依賴不可避免的會調用失敗,比如超時、異常等Hystrix能夠保證在一個依賴出問題的情況下, 不會導致整體服務失敗,避免級聯故障,以提高分佈式系統的彈性。
  • “斷路器”本身是一種開關裝置,當某個服務單元發生故障之後,通過斷路器的故障監控(類似熔斷保險絲),向調用方返回一個符合預期的、可處理的備選響應(FallBack) ,而不是長時間的等待或者拋出調用方無法處理的異常,這樣就保證了服務調用方的線程不會被長時間、不必要地佔用,從而避免了故障在分佈式系統中的蔓延,乃至雪崩。

多個微服務之間調用的時候,假設微服務A調用微服務B和微服務C,微服務B和微服務C又調用其它的微服務,這就是所謂的“扇出”。如果扇出的鏈路上某個微服務的調用響應時間過長或者不可用,對微服務A的調用就會佔用越來越多的系統資源,進而引起系統崩潰,所謂的“雪崩效應”.

對於高流量的應用來說,單一的後端依賴可能會導致所有服務器上的所有資源都在幾秒鐘內飽和。比失敗更糟糕的是,這些應用程序還可能導致服務之間的延遲增加,備份隊列,線程和其他系統資源緊張,導致整個系統發生更多的級聯故障。這些都表示需要對故障和延遲進行隔離和管理,以便單個依賴關係的失敗,不能取消整個應用程序或系統。

  • 可以幹嘛:服務降級,服務熔斷,服務限流,接近實時監控

2:服務熔斷

  • 熔斷機制是應對雪崩效應的一種微服務鏈路保護機制。
  • 過程:服務降級-》進而熔斷-》恢復調用鏈路
  • 當扇出鏈路的某個微服務不可用或者響應時間太時,會進行服務的降級,進而熔斷該節點微服務的調用,快速返回"錯誤”的響應信息。當檢測到該節點微服務調用響應正常後恢復調用鏈路。在SpringCloud框架裏熔斷機制通過Hystrix實現。 Hystrix會監控微服務間調用的狀況,當失敗的調用到一定閾值,缺省是5秒內20次調用失敗就會啓動熔斷機制。熔斷機制的註解是@HystrixCommand.
  • 使用@HystrixCommand.,需要在pom文件中引入如下maven
<!-- hystrix -->
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-hystrix</artifactId>
		</dependency>
  • 熔斷類型
熔斷打開:
請求不再進行調用當前服務。內部設置時鐘-般爲MTTR (平均故障處理時間)。當打開時長達到所設時鐘則進入半熔斷狀態
熔斷關閉:
熔斷關閉不會對服務進行熔斷
熔斷半開:
部分請求根據規則調用當的服務,如果請求成功目符合規則則認爲當前服務恢復正常,關閉熔斷
  • 斷路器開關或者關閉條件
1:當滿足一定的閥值的時候(默認10秒內超過20個請求次數)
2:當失敗率達到一定的時候(默認10秒內超過50%的請求失敗)
3:到達以上閥值,斷路器將會開啓
4:當開啓的時候,所有請求都不會進行轉發
5:一段時間之後(默認是5秒),這個時候斷路器是半開狀態,會讓其中一個請求進行轉發。如果成功,斷路器會關閉,若失敗,繼續開啓。
  • 斷路器在什麼情況起作用?

如下報錯,就會調用註解@HystrixCommand,斷路器就起作用了

涉及到斷路器的三個重要參數:快照時間窗、請求總數閥值、錯誤百分比閥值。
1:快照時間窗(sleepWindowInMilliseconds):斷路器確定是否打開需要統計-些請求和錯誤數據,而統計的時間範圍就是快照時間窗,默認爲最近的10秒。
2:請求總數閥值(requestVolumeThreshold):在快照時間窗內,必須滿足請求總數閥值纔有資格熔斷。默認爲20,意味着在10秒內,如果該hystrix命令的調用次數不足20次,即使所有的請求都超時或其他原因失敗,斷路器都不會打開。
3:錯誤百分比閥值(errorThresholdPercentage):當請求總數在快照時間窗內超過了閥值,比如發生了30次調用,如果在這30次調用中,有15次發生了超時異常,也就是超過50%的錯誤百分比,在默認設定50%閥值情況下,這時候就會將斷路器打開。
// ================= 服務熔斷 ==================
    @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") // 失敗率達到多少後跳閘
    })
     public String paymentCircuitBreaker(Integer id) {
        if (id < 0) {
            throw new RuntimeException("******** id 不能爲負數 *********");
        }
        String simpleUUID = IdUtil.simpleUUID();
        return Thread.currentThread().getName() + "\t" + "調用成功, 流水號: " + simpleUUID;
    }
    public String paymentCircuitBreaker_fallback(Integer id) {
        return "******** id 不能爲負數 請稍後再試 o(╥﹏╥)o *********";
    }

DeptController.java

@RestController
public class DeptController
{
	@Autowired
	private DeptService service;
	@Autowired
	private DiscoveryClient client;

	@RequestMapping(value = "/dept/get/{id}", method = RequestMethod.GET)
	//一旦調用服務方法失敗並拋出了錯誤信息後,會自動調用@HystrixCommand標註好的fallbackMethod調用類中的指定方法
	@HystrixCommand(fallbackMethod = "processHystrix_Get")
	public Dept get(@PathVariable("id") Long id)
	{
		Dept dept = this.service.get(id);
		if (null == dept) {
			throw new RuntimeException("該ID:" + id + "沒有沒有對應的信息");
		}
		
		return dept;
	}

	public Dept processHystrix_Get(@PathVariable("id") Long id)
	{
		return new Dept().setDeptno(id).setDname("該ID:" + id + "沒有沒有對應的信息,null--@HystrixCommand")
				.setDb_source("no this database in MySQL");		
	}

當輸入地址查詢的時候,如果傳進來的id,找不到,就會拋出異常,然後會自動調用@HystrixCommand標註好的fallbackMethod調用類中的指定方法,如下

在這裏插入圖片描述

3:服務降級

關於服務降級的理論知識
程序運行異常,超時,服務熔斷觸發服務降級,線程池打滿都會導致服務降級
OrderHystrixController.java

全局服務降級

@RestController
@Slf4j
@DefaultProperties(defaultFallback = "paymentGlobalFallBack")
public class OrderHystrixController {
    @Resource
    private PaymentHystrixService paymentHystrixService;

    @GetMapping("/consumer/payment/hystrix/ok/{id}")
    public String ok(@PathVariable("id") Integer id) {
        return paymentHystrixService.paymentInfo_OK(id);
    }
@GetMapping("/consumer/payment/hystrix/timeout/{id}")
    @HystrixCommand
    public String timeout(@PathVariable("id") Integer id) {
        return paymentHystrixService.paymentInfo_TIMEOUT(id);
    }

    // 下面是全局fallback方法
    public String paymentGlobalFallBack() {
        return "全局異常信息處理,請稍後再試o(╥﹏╥)o";
    }
}

pom.xml

  <!-- hystrix -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
        </dependency>

通配服務降級
PaymentFallbackService .java

@Component
public class PaymentFallbackService implements PaymentHystrixService {
    @Override
    public String paymentInfo_OK(Integer id) {
        return "-------PaymentFallbackService fall back paymentInfo_OK, o(╥﹏╥)o";
    }

    @Override
    public String paymentInfo_TIMEOUT(Integer id) {
        return "-------PaymentFallbackService fall back paymentInfo_TIMEOUT, o(╥﹏╥)o";
    }
}

PaymentHystrixService .interface

@Component
@FeignClient(value = "CLOUD-PROVIDER-HYSTRIX-PAYMENT", fallback = PaymentFallbackService.class)
public interface PaymentHystrixService {
    @GetMapping("/payment/hystrix/ok/{id}")
    String paymentInfo_OK(@PathVariable("id") Integer id);

    @GetMapping("/payment/hystrix/timeout/{id}")
    String paymentInfo_TIMEOUT(@PathVariable("id") Integer id);

4:服務限流

  • 秒殺高併發等操作,嚴禁一窩蜂的過來擁擠,大家排隊,一秒鐘N個,有序進行

5:豪豬hystrixDashboard

  • 除了隔離依賴服務的調用以外,Hystrix還提供了準實時的調用監控(Hystrix Dashboard),Hystrix會持續地記錄所有通過Hystrix發起的請求的執行信息,並以統計報表和圖形的形式展示給用戶,包括每秒執行多少請求多少成功,多少失敗等。
  • Netflix通過hystrix-metrics-event-stream項目實現了對以上指標的監控。Spring Cloud也提供了Hystrix Dashboard的整合,對監控內容轉化成可視化界面。

監控(Hystrix Dashboard)的創建步驟
1:創建如下工程
在這裏插入圖片描述
2:pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>com.atstudying.springclound</groupId>
    <artifactId>microservicespringclound</artifactId>
    <version>0.0.1-SNAPSHOT</version>
  </parent>
  <artifactId>microservicecloud-consumer-hystrix-dashboard</artifactId>
  
  <dependencies>
		<!-- 自己定義的api -->
		<dependency><!-- 自己定義的api -->
			<groupId>com.atstudying.springclound</groupId>
			<artifactId>microserviceclound-api</artifactId>
			<version>${project.version}</version>
		</dependency>
		
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<!-- 修改後立即生效,熱部署 -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>springloaded</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
		</dependency>
		<!-- Ribbon相關 -->
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-eureka</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-ribbon</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-config</artifactId>
		</dependency>
		
		<!-- feign相關 -->
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-feign</artifactId>
		</dependency>
		
		<!-- hystrix和 hystrix-dashboard相關 -->
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-hystrix</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-hystrix-dashboard</artifactId>
		</dependency>
		
		
	</dependencies>
</project>

3:application.yml

server:
  port: 9001

4:DeptConsumer_DashBoard_App.java

@SpringBootApplication
@EnableHystrixDashboard
public class DeptConsumer_DashBoard_App
{
	public static void main(String[] args)
	{
		SpringApplication.run(DeptConsumer_DashBoard_App.class, args);
	}
}

5:測試
在這裏插入圖片描述
熔斷監控面板(Hystrix Dashboard)
總結:七色,一圈,一線
在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述

6:Hystrix 工作流程

Hystrix 工作流程

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章