SpringCloud之Hystrix應用實踐

使用SpringCloud的Hystrix功能,有幾種方式:

1、單應用監聽,也可以用於測試

引用包:

<!-- 斷路器監控-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<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>
斷路情況監控其實就是通過收集spring-boot-starter-actuator中的metric信息,所以他必須引入,這裏需要注意,如果你設置了management.contextPath參數,則需要在後面監控時加上相關路徑,比如我的爲/envmanager 否則會提示:Unable to connect to Command Metric Stream如下:


修改monitor地址後爲:


使用Hystrix示例:

@SpringBootApplication
@EnableDiscoveryClient
@EnableCircuitBreaker
@EnableHystrixDashboard
public class MonitorServerBoot {
    public static void main(String[] args) {
        SpringApplication.run(MonitorServerBoot.class,args);
    }
}
模擬調用失敗情況:

@Component
public class CallDependencyService {
    private Random random = new Random();
    /**
     * 模擬獲取用戶信息(通過網絡調用)
     * @return
     */
    @HystrixCommand(fallbackMethod = "fallback")
    public String mockGetUserInfo(){
        int randomInt= random.nextInt(10) ;
        if(randomInt<8){  //模擬調用失敗情況
            throw new RuntimeException("call dependency service fail.");
        }else{
            return "UserName:odeng;number:"+randomInt;
        }
    }

    public String fallback(){
        return "some exception occur call fallback method.";
    }
}

若想看到效果斷路效果,需要調用失敗服務

特別說明:

@EnableHystrix與@EnableCircuitBreaker效果一樣,都是EnableCircuitBreaker,所以建議直接使用@EnableCircuitBreaker註解
@HystrixCommand註解與@EnableCircuitBreaker配合使用,否則無效

如果你使用了feign,feign是自帶斷路器的,並且是已經打開了。如果使用feign不想用斷路器的話,可以在配置文件中關閉它,配置如下:feign.hystrix.enabled=false


如果這個區域一直爲loading..... 表示很可能沒有使用線程隔離方式,而是信號模式

hystrix.command.default.execution.isolation.strategy= THREAD|SEMAPHORE

應用場景選擇:

線程池隔離: 
1、 第三方應用或者接口 
2、 併發量大

信號量隔離: 
1、 內部應用或者中間件(redis) 
2、 併發需求不大

Hystrix 參數詳解

hystrix.command.default和hystrix.threadpool.default中的default爲默認CommandKey

Command Properties

Execution相關的屬性的配置:

  • hystrix.command.default.execution.isolation.strategy 隔離策略,默認是Thread, 可選Thread|Semaphore

    • thread 通過線程數量來限制併發請求數,可以提供額外的保護,但有一定的延遲。一般用於網絡調用
    • semaphore 通過semaphore count來限制併發請求數,適用於無網絡的高併發請求
  • hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds 命令執行超時時間,默認1000ms

  • hystrix.command.default.execution.timeout.enabled 執行是否啓用超時,默認啓用true
  • hystrix.command.default.execution.isolation.thread.interruptOnTimeout 發生超時是是否中斷,默認true
  • hystrix.command.default.execution.isolation.semaphore.maxConcurrentRequests 最大併發請求數,默認10,該參數當使用ExecutionIsolationStrategy.SEMAPHORE策略時纔有效。如果達到最大併發請求數,請求會被拒絕。理論上選擇semaphore size的原則和選擇thread size一致,但選用semaphore時每次執行的單元要比較小且執行速度快(ms級別),否則的話應該用thread。
    semaphore應該佔整個容器(tomcat)的線程池的一小部分。

Fallback相關的屬性

這些參數可以應用於Hystrix的THREAD和SEMAPHORE策略

  • hystrix.command.default.fallback.isolation.semaphore.maxConcurrentRequests 如果併發數達到該設置值,請求會被拒絕和拋出異常並且fallback不會被調用。默認10
  • hystrix.command.default.fallback.enabled 當執行失敗或者請求被拒絕,是否會嘗試調用hystrixCommand.getFallback() 。默認true

Circuit Breaker相關的屬性

  • hystrix.command.default.circuitBreaker.enabled 用來跟蹤circuit的健康性,如果未達標則讓request短路。默認true
  • hystrix.command.default.circuitBreaker.requestVolumeThreshold 一個rolling window內最小的請求數。如果設爲20,那麼當一個rolling window的時間內(比如說1個rolling window是10秒)收到19個請求,即使19個請求都失敗,也不會觸發circuit break。默認20
  • hystrix.command.default.circuitBreaker.sleepWindowInMilliseconds 觸發短路的時間值,當該值設爲5000時,則當觸發circuit break後的5000毫秒內都會拒絕request,也就是5000毫秒後纔會關閉circuit。默認5000
  • hystrix.command.default.circuitBreaker.errorThresholdPercentage錯誤比率閥值,如果錯誤率>=該值,circuit會被打開,並短路所有請求觸發fallback。默認50
  • hystrix.command.default.circuitBreaker.forceOpen 強制打開熔斷器,如果打開這個開關,那麼拒絕所有request,默認false
  • hystrix.command.default.circuitBreaker.forceClosed 強制關閉熔斷器 如果這個開關打開,circuit將一直關閉且忽略circuitBreaker.errorThresholdPercentage

Metrics相關參數

  • hystrix.command.default.metrics.rollingStats.timeInMilliseconds 設置統計的時間窗口值的,毫秒值,circuit break 的打開會根據1個rolling window的統計來計算。若rolling window被設爲10000毫秒,則rolling window會被分成n個buckets,每個bucket包含success,failure,timeout,rejection的次數的統計信息。默認10000
  • hystrix.command.default.metrics.rollingStats.numBuckets 設置一個rolling window被劃分的數量,若numBuckets=10,rolling window=10000,那麼一個bucket的時間即1秒。必須符合rolling window % numberBuckets == 0。默認10
  • hystrix.command.default.metrics.rollingPercentile.enabled 執行時是否enable指標的計算和跟蹤,默認true
  • hystrix.command.default.metrics.rollingPercentile.timeInMilliseconds 設置rolling percentile window的時間,默認60000
  • hystrix.command.default.metrics.rollingPercentile.numBuckets 設置rolling percentile window的numberBuckets。邏輯同上。默認6
  • hystrix.command.default.metrics.rollingPercentile.bucketSize 如果bucket size=100,window=10s,若這10s裏有500次執行,只有最後100次執行會被統計到bucket裏去。增加該值會增加內存開銷以及排序的開銷。默認100
  • hystrix.command.default.metrics.healthSnapshot.intervalInMilliseconds 記錄health 快照(用來統計成功和錯誤綠)的間隔,默認500ms

Request Context 相關參數

hystrix.command.default.requestCache.enabled 默認true,需要重載getCacheKey(),返回null時不緩存
hystrix.command.default.requestLog.enabled 記錄日誌到HystrixRequestLog,默認true

Collapser Properties 相關參數

hystrix.collapser.default.maxRequestsInBatch 單次批處理的最大請求數,達到該數量觸發批處理,默認Integer.MAX_VALUE
hystrix.collapser.default.timerDelayInMilliseconds 觸發批處理的延遲,也可以爲創建批處理的時間+該值,默認10
hystrix.collapser.default.requestCache.enabled 是否對HystrixCollapser.execute() and HystrixCollapser.queue()的cache,默認true

ThreadPool 相關參數

線程數默認值10適用於大部分情況(有時可以設置得更小),如果需要設置得更大,那有個基本得公式可以follow:
requests per second at peak when healthy × 99th percentile latency in seconds + some breathing room
每秒最大支撐的請求數 (99%平均響應時間 + 緩存值)
比如:每秒能處理1000個請求,99%的請求響應時間是60ms,那麼公式是:
1000 
(0.060+0.012)

基本得原則時保持線程池儘可能小,他主要是爲了釋放壓力,防止資源被阻塞。
當一切都是正常的時候,線程池一般僅會有1到2個線程激活來提供服務

  • hystrix.threadpool.default.coreSize 併發執行的最大線程數,默認10
  • hystrix.threadpool.default.maxQueueSize BlockingQueue的最大隊列數,當設爲-1,會使用SynchronousQueue,值爲正時使用LinkedBlcokingQueue。該設置只會在初始化時有效,之後不能修改threadpool的queue size,除非reinitialising thread executor。默認-1。
  • hystrix.threadpool.default.queueSizeRejectionThreshold 即使maxQueueSize沒有達到,達到queueSizeRejectionThreshold該值後,請求也會被拒絕。因爲maxQueueSize不能被動態修改,這個參數將允許我們動態設置該值。if maxQueueSize == -1,該字段將不起作用
  • hystrix.threadpool.default.keepAliveTimeMinutes 如果corePoolSize和maxPoolSize設成一樣(默認實現)該設置無效。如果通過plugin(https://github.com/Netflix/Hystrix/wiki/Plugins)使用自定義實現,該設置纔有用,默認1.
  • hystrix.threadpool.default.metrics.rollingStats.timeInMilliseconds 線程池統計指標的時間,默認10000
  • hystrix.threadpool.default.metrics.rollingStats.numBuckets 將rolling window劃分爲n個buckets,默認10

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