(七)SpringBoot+SpringCloud —— 集成斷路器

斷路器簡介

在一個項目中,系統可能被拆分紅多個服務,例如用戶、訂單和庫存等。java

這裏存在這服務調用服務的狀況,例如,客戶端調用訂單服務,訂單服務又調用庫存服務。git

此時若庫存服務響應緩慢,會直接致使訂單服務的線程被掛起,以等待庫存申請服務的響應,在漫長的等待以後用戶會由於請求庫存失敗而獲得建立訂單失敗的結果。github

若是在高併發下,因這些掛起的線程在等待庫存服務的響應而未能得到釋放,會似的後續到來的請求被阻塞,最終致使訂單服務也不可用。web

在分佈式架構中,斷路器模式的做用也是相似的,當某個服務單元發生故障以後,經過斷路器的故障監控,向調用方返回一個錯誤響應,而不是漫長的等待。spring

快速入門

首先,添加斷路器hystrix的依賴。緩存

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

接着在工程的主類,添加註解@EnableCircuitBreaker:架構

package cn.net.bysoft.owl.bookstore.web.console;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
@EnableDiscoveryClient
@EnableCircuitBreaker
public class OwlBookstoreWebConsoleApplication {

    @Bean
    @LoadBalanced
    RestTemplate restTemplate() {
        return new RestTemplate();
    }

    public static void main(String[] args) {
        SpringApplication.run(OwlBookstoreWebConsoleApplication.class, args);
    }
}

接着,就能夠使用斷路器了,能夠添加@HystrixCommand註解,對調用服務的方法進行修飾:併發

@HystrixCommand(fallbackMethod = "findByIdFallback")
	public User findById(Long id) {
		UriComponents uriComponents = UriComponentsBuilder.fromUriString("http://SERVICE-USER/users/{id}").build()
				.expand(id).encode();
		URI uri = uriComponents.toUri();
		return restTemplate.getForObject(uri, User.class);
	}
	
	public User findByIdFallback(Long id) {
		return null;
	}

fallbackMethod是服務發生異常時,回調的降級處理函數,該函數的參數和返回值要與調用函數一致。分佈式

斷路器的默認超時時間爲2000毫秒。當被斷路器修飾的函數執行超過這個值,將觸發斷路器的服務降級,該參數是能夠設置的。函數

斷路器配置

全局配置屬性:hystrix.[attr].default.

實例配置屬性:hystrix.[attr].[key].

execution配置

  1. Command Properties
    1. Execution
      1. execution.isolation.strategy (執行的隔離策略)
      2. execution.isolation.thread.timeoutInMilliseconds(執行的超時時間)
      3. execution.timeout.enabled(是否啓用超時時間)
      4. execution.isolation.thread.interruptOnTimeout(超時發生後是否要中斷該服務)
      5. execution.isolation.thread.interruptOnCancel(執行被取消後是否要中斷該服務)
      6. execution.isolation.semaphore.maxConcurrentRequests(當最大併發達到該值,後續的請求會被拒絕)
    2. Fallback
      1. fallback.isolation.semaphore.maxConcurrentRequests(fallback方法執行的最大併發請求數,當達到最大,後續的請求將會被拒絕並拋出異常)
      2. fallback.enabled(服務降級策略是否啓用)
    3. Circuit Breaker
      1. circuitBreaker.enabled (斷路器開關)
      2. circuitBreaker.requestVolumeThreshold (斷路器請求閾值)
      3. circuitBreaker.sleepWindowInMilliseconds(斷路器休眠時間)
      4. circuitBreaker.errorThresholdPercentage(斷路器錯誤請求百分比)
      5. circuitBreaker.forceOpen(斷路器強制開啓)
      6. circuitBreaker.forceClosed(斷路器強制關閉)
    4. Metrics
      1. metrics.rollingStats.timeInMilliseconds(滾動時間窗長度,毫秒級)
      2. metrics.rollingStats.numBuckets(滾動時間窗統計指標信息時劃分「桶」的數量)
      3. metrics.rollingPercentile.enabled(對命令執行的延遲是否使用百分位數來跟蹤和計算)
      4. metrics.rollingPercentile.timeInMilliseconds(設置百分位統計的滾動窗口的持續時間)
      5. metrics.rollingPercentile.numBuckets(設置百分位統計滾動窗口中使用「桶」的數量)
      6. metrics.rollingPercentile.bucketSize(設置在執行過程當中每一個「桶」中保留的最大執行次數)
      7. metrics.healthSnapshot.intervalInMilliseconds(採集健康快照的間隔等待時間)
    5. Request Context
      1. requestCache.enabled(是否啓用緩存)
      2. requestLog.enabled(執行的時間是否打印到日誌)
  2. Collapser Properties
    1. maxRequestsInBatch(請求合併批處理中容許的最大請求數)
    2. timerDelayInMilliseconds(批處理過程當中每一個命令延遲的時間,毫秒級)
    3. requestCache.enabled(是否開啓請求緩存)
  3. Thread Pool Properties
    1. coreSize(線程池大小)
    2. maxQueueSize(最大隊列數量)
    3. queueSizeRejectionThreshold (隊列大小拒絕閾值)
    4. metrics.rollingStats.timeInMilliseconds(滾動時間窗的長度,毫秒級)
    5. metrics.rollingStats.numBuckets(滾動時間窗被劃分的數量)

Github

https://github.com/XuePeng87/owl-bookstore

相關文章
相關標籤/搜索