前言
本文主要研究一下 spring cloud gateway 如何集成 hystrix。
當下游接口負載很大,或者接口不通等其他原因導致超時,如果接口不熔斷的話將會影響到下游接口得不到喘息,網關也會因為超時連接一直掛起,很可能因為一個子系統的問題導致整個系統的雪崩。所以我們的網關需要設計熔斷,當因為熔斷器打開時,網關將返回一個降級的應答。
Maven 配置
添加 hystrix 依賴
pom.xml
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
項目實戰
- 在
provider1服務中添加一個方法,延時 2 秒返回響應。
@GetMapping("/timeout")
public String timeout() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("休眠了2秒");
return "timeout test";
}
- 修改網關配置文件
server:
port: 2000
spring:
application:
name: idc-gateway2
redis:
host: localhost
port: 6379
timeout: 6000ms # 連接超時時長(毫秒)
jedis:
pool:
max-active: 1000 # 連接池最大連接數(使用負值表示沒有限制)
max-wait: -1ms # 連接池最大阻塞等待時間(使用負值表示沒有限制)
max-idle: 10 # 連接池中的最大空閑連接
min-idle: 5 # 連接池中的最小空閑連接
cloud:
consul:
host: localhost
port: 8500
gateway:
discovery:
locator:
enabled: true # gateway可以通過開啟以下配置來打開根據服務的serviceId來匹配路由,默認是大寫
routes:
- id: provider1
uri: lb://idc-provider1
predicates:
- Path=/p1/**
filters:
- StripPrefix=1
- name: Hystrix
args:
name: default
fallbackUri: forward:/defaultfallback # 只有該id下的服務會降級
- id: provider2
uri: lb://idc-provider2
predicates:
- Path=/p2/**
filters:
- StripPrefix=1
# hystrix 信號量隔離,1.5秒后自動超時
hystrix:
command:
default:
execution:
isolation:
strategy: SEMAPHORE
thread:
timeoutInMilliseconds: 1500
- 網關添加降級處理類
@RestController
public class FallbackController {
@RequestMapping("/defaultfallback")
public Map<String,Object> defaultfallback(){
System.out.println("降級操作...");
Map<String,Object> map = new HashMap<>();
map.put("code",200);
map.put("msg","服務超時降級");
map.put("data",null);
return map;
}
}
降級測試
- 超時服務降級
curl http://localhost:2000/p1/timeout
返回
{"msg":"服務超時降級","code":200,"data":null}
- 其他異常
spring-cloud-gateway 調用下游服務返回的異常,網關不做任何處理,會直接返回。大家想一下為什么在網關不去處理下游異常呢? 因為很多時候下游的異常是包含有效信息的(異常信息千千萬),如果在網關處做了統一返回,就失去了返回異常的意義。
spring-cloud-starter-netflix-hystrix 內置的 Hystrix 過濾器是
HystrixGatewayFilterFactory。 感興趣的小伙伴可以自行閱讀相關源碼。
結語
本文到此結束,感謝大家的閱讀。歡迎大家關注公眾號【當我遇上你】。
