在項目中使用spring cloud gateway之后中,發現第一次路由請求都會失敗。
百度了一下,知道是hystix timeout的問題:
即Hystrix默認的超時時間是1秒,如果超過這個時間尚未響應,將會進入fallback代碼。
而首次請求往往會比較慢(因為Spring的懶加載機制,要實例化一些類),這個響應時間可能就大於1秒了。
一般有三種解決方案:
1)延長hystix的連接超時時間,默認時間是1秒
//在Fegion服務的application配置文件中添加一下配置: hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds:5000
2)禁用hystix的超時時間
//在Fegion服務的application配置文件中添加一下配置: hystrix.command.default.execution.timeout.enabled: false
3)直接禁用hystix
//在Fegion服務的application配置文件添加如下配置信息: feign.hystrix.enabled: false
個人感覺第2/3方案都太簡單粗暴了,后面也會出現其他問題,所以先試試第1個方案。
為了對hystrix timeout了解更清楚,避免碰到其他坑,再次百度,總結hystrix配置如下
最終解決方案,如果配置文件的版本基本如方案1所寫(並未測試),由於我的網關使用代碼編寫的,最終如下
@Bean public RouteLocator customRouteLocator(RouteLocatorBuilder builder) { Builder result=builder.routes(); //services列表 for (int i = 0; i < services.length; i++) { String service = services[i]; result=result.route(p -> p .path("/"+service+"/**") .filters(f -> f .hystrix(config -> config // 對path()指定的請求使用熔斷器 .setName("hystrix-"+service) // 熔斷器的名字 .setFallbackUri("forward:/fallback")// 熔斷 .setSetter(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey(service)) .andCommandPropertiesDefaults(HystrixCommandProperties.Setter() .withExecutionTimeoutInMilliseconds(5000))//超時 ))) .uri("lb://"+service)); // 將請求路由到指定目標, lb開頭是注冊中心中的服務 } return result.build(); }