spring cloud gateway集成hystrix全局斷路器操作
pom.xml添加依賴
<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-netflix-hystrix</artifactId></dependency>在配置文件中,增加spring.cloud.gateway.default-filters:
default-filters:- name: Hystrix args: name: fallbackcmd fallbackUri: forward:/fallbackcontroller
一定要注意是spring.cloud.gateway.default-filters這個配置節。
如上的配置,將會使用HystrixCommand打包剩余的過濾器,并命名為fallbackcmd,我們還配置了可選的參數fallbackUri,降級邏輯被調用,請求將會被轉發到URI為/fallbackcontroller的控制器處理。
定義降級處理如下:@RequestMapping(value = '/fallbackcontroller')public Map<String, String> fallBackController() { Map<String, String> res = new HashMap(); res.put('code', '-100'); res.put('data', 'service not available'); return res;}
此時可以設置hystrix超時時間(毫秒) ,默認只有2秒
hystrix: command: default: execution:isolation: thread: timeoutInMilliseconds: 30000
示例代碼:
https://github.com/wanghongqi/springcloudconsul_test/tree/master/springtest_gateway
spring cloud gateway 全局熔斷熔斷主要保護的是調用方服務,如某A服務調用B服務的rpc接口,突然B服務接口不穩定,表現為接口延遲或者失敗率變大。
這個時候如果對B服務調用不能快速失敗,那么會導致A服務大量線程資源無法釋放導致最終A服務不穩定,故障點由B服務傳遞到A服務,故障擴大。
熔斷就是在B服務出現故障的情況下,斷開對B的調用,通過快速失敗來保證A服務的穩定。
一:Gateway項目maven引入依賴包Spring Cloud Gateway 利用 Hystrix 的熔斷特性,在流量過大時進行服務降級,同樣我們還是首先給項目添加上依賴
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId></dependency>二:創建熔斷后轉發的請求
@RestControllerpublic class FallbackController { private Logger log= LoggerFactory.getLogger(getClass()); @RequestMapping('/error/fallback') public Object fallacak(){log.info('熔斷處理!!!');return 'Service Error!!!'; }}三:yml配置
#全局熔斷攔截器default-filters: - name: Hystrix args:name: fallbackcmdfallbackUri: forward:/error/fallback - name: Retry args:retries: 3statuses: BAD_GATEWAY,BAD_REQUESTmethods: GET,POST
Hystrix是Gateway以封裝好的過濾器。如果不了解請查看:GatwayFilter工廠
name:即HystrixCommand的名字
fallbackUri:forward:/error/fallback 配置了 fallback 時要會調的路徑,當調用 Hystrix 的 fallback 被調用時,請求將轉發到/error/fallback 這個 URI
Retry 通過這四個參數來控制重試機制: retries, statuses, methods, 和 series
retries:重試次數,默認值是 3 次
statuses:HTTP 的狀態返回碼,取值請參考:org.springframework.http.HttpStatus
methods:指定哪些方法的請求需要進行重試邏輯,默認值是 GET 方法,取值參考:org.springframework.http.HttpMethod
series:一些列的狀態碼配置,取值參考:org.springframework.http.HttpStatus.Series。符合的某段狀態碼才會進行重試邏輯,默認值是 SERVER_ERROR,值是 5,也就是 5XX(5 開頭的狀態碼),共有5 個值。
# hystrix 信號量隔離,3秒后自動超時hystrix: command:fallbackcmd: execution:isolation: strategy: SEMAPHORE thread:timeoutInMilliseconds: 3000
fallbackcmd 此處需要和上面設置的HystrixCommand一致
timeoutInMilliseconds 設置超時時間
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持好吧啦網。
相關文章: