學習SpringCloud之斷路器Hystrix

簡介

  • 什麼是斷路器?
    斷路器就是爲了解決微服務架構中的“雪崩”現象,即某個服務出現問題會導致其他服務阻塞,嚴重最終會導致服務器癱瘓。
    當服務出現問題是,斷路器會負責斷開這個該服務的依賴,以防止問題蔓延,保護整體服務。

  • Hystrix也是SpringCloudNetflix微服務套件中的一個組件,作爲斷路器的角色。

image

以下示例均基於SpringCloud的Greenwich.SR1版本。

基礎依賴

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

Hystrix

@EnableHystrix 修飾啓動一個SpringBoot應用。

@SpringBootApplication
@EnableHystrix
class HystrixClientStarter

fun main(args: Array<String>) {
    runApplication<HystrixClientStarter>(*args)
}

application.yml配置

server:
  port: 6602

spring:
  application:
    name: hystrix-client

再寫一個簡單的Controller來試一下效果。

@RestController
class DemoController {

    @RequestMapping("hello")
    @HystrixCommand(fallbackMethod = "fallback")
    fun hello(@RequestParam("name") name: String): String {
        throw Exception("test exception")               // throw test exception here
        return "hello $name."
    }


    fun fallback(name: String): String {
        return "fallback function: hello $name."
    }
}

@HystrixCommand 註解來爲一個方法增加熔斷的能力。只需要定義一個和目標方法(上述例子爲hello())結構一致的方法,在註解中傳入即可。
爲了測試,目標方法中故意拋了一個異常來模擬微服務異常。
訪問 http://localhost:6602/hello?name=czb1n 會顯示:

fallback function: hello czb1n.

HystrixDashboard

Hystrix還提供了一個數據指標面板工具,HystrixDashboard。不過這個工具沒有在Hystrix包裏,需要另外導入。

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

啓動類中要增加 @EnableHystrixDashboard 註解來啓動面板。
面板中的指標數據來自於SpringBoot的actuator
所以要加入actuator的依賴的同時,還要修改application.yml來暴露Hystrix相關的節點指標。

management:
  endpoints:
    web:
      exposure:
        include: hystrix.stream

啓動訪問http://localhost:6602/actuator/hystrix.stream 就可以看到指標數據。
訪問 http://localhost:6602/hystrix 就能打開HystrixDashboard的界面。輸入上述的stream就能監控對應的指標。

image

其他

圖片均來自SpringCloudNetflix官方文檔

示例代碼地址: https://github.com/czb1n/learn-spring-cloud-with-kotlin

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