造成該問題的原因
Hystrix默認的超時時間是1秒,如果超過這個時間尚未響應,將會進入fallback代碼。而首次請求往往會比較慢(由於Ribbon是懶加載的,在首次請求時,纔會開始初始化相關類),因此在一些機器特別是配置低的機器上,首次請求的響應時間可能就大於1秒了。
知道原因後,我們來總結一下解決方案。以feign爲例,解決方案有如下四種。
方法一、將Hystrix超時時間,示例
hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds: 5000
該配置讓Hystrix的超時時間改爲5秒
方法二、禁用Hystrix的超時
hystrix.command.default.execution.timeout.enabled: false
方法三、爲Feign禁用Hystrix
全局禁用(不推薦)
feign.hystrix.enabled: false
局部禁用
爲名爲microservice-provider-user
的Feign Client禁用Hystrix
@FeignClient(name = "microservice-provider-user")
public interface UserFeignClient {
@GetMapping("/users/{id}")
User findById(@PathVariable("id") Long id);
}
class FooConfiguration {
@Bean
@Scope("prototype")
public Feign.Builder feignBuilder(){
return Feign.builder();
}
}
方法四、Ribbon配置飢餓加載(最佳)
從Dalston開始,Ribbon支持配置eager load實現在啓動時就初始化Ribbon相關類
ribbon:
eager-load:
enabled: true
clients: client1, client2, client3